## enemy.gd
# Enemy character script. Each turn, chases the player one tile using pathfinding.
class_name Enemy
extends Character

# Movement speed in pixels per second.
const SPEED: float = 200.0
# Distance threshold for snapping to a tile (prevents jitter).
const ARRIVAL_THRESHOLD: float = 4.0

# Reference to the player — set by LevelManager after spawning.
var _player: Player
# True while animating toward _move_target.
var _is_moving: bool = false
# World position of the tile this enemy is stepping toward.
var _move_target: Vector2 = Vector2.ZERO


# Called by TurnManager. Pathfinds to the player and steps one tile closer.
func take_turn() -> void:
	var my_tile := LevelManager.world_to_tile(position)
	var player_tile := LevelManager.world_to_tile(_player.position)
	var path := LevelManager.find_path(my_tile, player_tile)
	# path[0] is own tile; path[-1] is the player's tile (don't step there).
	if path.size() < 2:
		turn_finished.emit()
		return
	# Stop one tile away from the player — don't overlap.
	if path.size() == 2:
		turn_finished.emit()
		return
	_move_target = LevelManager.tile_to_world(path[1])
	_is_moving = true


# Glides toward _move_target each frame. Emits turn_finished on arrival.
func _physics_process(_delta: float) -> void:
	if not _is_moving:
		velocity = Vector2.ZERO
		move_and_slide()
		return

	var to_target: Vector2 = _move_target - position

	if to_target.length() < ARRIVAL_THRESHOLD:
		position = _move_target
		velocity = Vector2.ZERO
		move_and_slide()
		_is_moving = false
		turn_finished.emit()
	else:
		velocity = to_target.normalized() * SPEED
		move_and_slide()
