extends CharacterBody2D

@export var speed: float = 1000.0
@onready var interact_ray: RayCast2D = $RayCast2D

var facing: Vector2 = Vector2.DOWN

func _ready() -> void:
	interact_ray.add_exception(self)

func _physics_process(_delta: float) -> void:
	if Game.is_dialogue_active:
		velocity = Vector2.ZERO
		move_and_slide()
		return

	var dir := Vector2(
		Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
		Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
	)

	# Undertale-ish facing (4-dir) so interaction is reliable
	if dir != Vector2.ZERO:
		if abs(dir.x) > abs(dir.y):
			facing = Vector2(sign(dir.x), 0)
		else:
			facing = Vector2(0, sign(dir.y))

	velocity = dir.normalized() * speed
	move_and_slide()

	_update_interact_ray()

	if Input.is_action_just_pressed("interact"):
		_try_interact()

func _update_interact_ray() -> void:
	interact_ray.target_position = facing * 40.0

func _try_interact() -> void:
	interact_ray.force_raycast_update()
	if not interact_ray.is_colliding():
		return

	var obj := interact_ray.get_collider()
	if obj and obj.has_method("interact"):
		obj.interact(self)
