extends CharacterBody2D
class_name Player

@onready var interaction_ray_cast: RayCast2D = %InteractionRayCast

# Player movement speed (pixels per second)
@export var speed = 200

@export var friction = 16

# Rotation speed (radians per second) - adjust for desired rotation speed
@export var rotation_speed = PI * 4 # Rotate 2 full circles per second

# Use mouse for rotation? If false, uses gamepad right stick.
@export var rotate_with_mouse = true

@export var interacting_state: Player_State = Player_State_Standard.new()

func _physics_process(delta):
	# --- Movement Logic ---
	var input_vector := Input.get_vector("move_left", "move_right", "move_up", "move_down")

	if input_vector != Vector2.ZERO:
		if not interacting_state.restrict_movement():
			velocity = input_vector * speed
		interacting_state.on_movement_input(input_vector, self)
	else:
		velocity = lerp(velocity, Vector2.ZERO, friction * delta)
		
	move_and_slide()

	# --- Rotation Logic ---
	var target_rotation_direction = Vector2.ZERO

	if rotate_with_mouse:
		var mouse_position = get_global_mouse_position()
		target_rotation_direction = global_position.direction_to(mouse_position)
	else:
		target_rotation_direction = Input.get_vector("rotate_left", "rotate_right", "rotate_up", "rotate_down")

	if target_rotation_direction != Vector2.ZERO:
		var target_angle := target_rotation_direction.angle()
		if not interacting_state.restrict_rotation():
			rotation = lerp_angle(rotation, target_angle, rotation_speed * delta)
		interacting_state.on_rotation_input(target_angle, self)
	
	# --- Interact Logic ---
	if Input.is_action_just_pressed("interact"):
		if interaction_ray_cast.is_colliding():
			var interaction_target = interaction_ray_cast.get_collider()
			if interaction_target is InteractableBody:
				interaction_target.interact(self)
