extends Area2D

signal ufo_destroyed(pos)
signal ufo_bullet_fired(pos, angle)

const SCREEN = Vector2(640, 640)

@export var speed:         float = 110.0
@export var shoot_interval: float = 2.2

var _shoot_timer: float = 1.0
var _dir:         Vector2 = Vector2.RIGHT
var _change_timer: float  = 0.0
var _frame_timer:  float  = 0.0
var alive:         bool   = true

@onready var sprite: AnimatedSprite2D = $Sprite


func _ready() -> void:
	sprite.play("fly")
	# Pick a random horizontal direction to enter from
	var from_left = randi() % 2 == 0
	position.x = -30.0 if from_left else SCREEN.x + 30
	position.y = randf_range(60, SCREEN.y - 60)
	_dir = Vector2(1, 0) if from_left else Vector2(-1, 0)


func _process(delta: float) -> void:
	if not alive:
		return

	# Weave up/down a bit
	_change_timer -= delta
	if _change_timer <= 0:
		_change_timer = randf_range(0.8, 2.0)
		_dir.y = randf_range(-0.6, 0.6)

	position += _dir.normalized() * speed * delta

	# Wrap vertically, exit when off horizontal edge
	position.y = wrapf(position.y, -20, SCREEN.y + 20)
	if position.x < -60 or position.x > SCREEN.x + 60:
		queue_free()
		return

	# Shoot toward player
	_shoot_timer -= delta
	if _shoot_timer <= 0:
		_shoot_timer = shoot_interval
		var ship_nodes = get_tree().get_nodes_in_group("ship")
		if not ship_nodes.is_empty():
			var target = ship_nodes[0].global_position
			var angle = (target - global_position).angle() + PI/2
			ufo_bullet_fired.emit(global_position, angle)


func die() -> void:
	if not alive:
		return
	alive = false
	ufo_destroyed.emit(global_position)
	queue_free()
