extends Node2D

@export var min_distance := 250.0
@export var rotation_speed := 8.0

var _target_pos: Vector2
var _has_target := false

func _process(delta: float) -> void:
	_find_target()
	_update_rotation(delta)

func _find_target() -> void:
	var enemies = get_tree().get_nodes_in_group("enemy")
	var closest_enemy: Node2D = null
	var shortest_dist := INF

	for enemy in enemies:
		if enemy is Node2D:
			var dist = global_position.distance_to(enemy.global_position)
			if dist < shortest_dist:
				shortest_dist = dist
				closest_enemy = enemy

	if closest_enemy and shortest_dist > min_distance:
		_target_pos = closest_enemy.global_position
		_has_target = true
		visible = true
	else:
		_has_target = false
		visible = false

func _update_rotation(delta: float) -> void:
	if not _has_target:
		return

	var desired_angle = global_position.angle_to_point(_target_pos)
	rotation = lerp_angle(rotation, desired_angle, rotation_speed * delta)
