## player.gd
# Player character script. Handles input, pathfinding, and movement.
class_name Player
extends Character

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


# The current path (as a list of tile coordinates) the player is following.
var _path: Array[Vector2i] = []


# Handles mouse input for movement. Calculates a path to the clicked tile.
func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		var clicked_tile: Vector2i = LevelManager.world_to_tile(get_global_mouse_position())
		var current_tile: Vector2i = LevelManager.world_to_tile(position)
		_path = LevelManager.find_path(current_tile, clicked_tile)
		# Drop the first entry — it's the tile the player is already on.
		if not _path.is_empty():
			_path.remove_at(0)

# Moves the player along the path, one tile at a time, using velocity.
func _physics_process(_delta: float) -> void:
	if _path.is_empty():
		velocity = Vector2.ZERO
		move_and_slide()
		return

	var target_world: Vector2 = LevelManager.tile_to_world(_path[0])
	var to_target: Vector2 = target_world - position

	if to_target.length() < ARRIVAL_THRESHOLD:
		position = target_world
		_path.remove_at(0)
	else:
		velocity = to_target.normalized() * SPEED
		move_and_slide()
