class_name Player
extends CharacterBody3D

@export var speed: float = 5.0
@export var rotation_speed: float = 0.1
@export var gravity: float = 9.8
@export var jump_velocity: float = 5.0

var target_rotation_y: float = rotation.y

@onready var area = $Area3D
@onready var anim = $Model/AnimationPlayer

enum CharacterState
{
	IDLE,
	WALKING,
	JUMPING,
}

func _ready() -> void:
	LevelManager.current_checkpoint = global_position
	LevelManager.player = self

func handle_animation(_state: CharacterState) -> void:
	var anim_name: String
	match _state:
		CharacterState.IDLE: anim_name = "PlayerLibrary/IdlePose"
		CharacterState.JUMPING: anim_name = "PlayerLibrary/Jump"
		CharacterState.WALKING: anim_name = "PlayerLibrary/Walk"

	if anim.current_animation != anim_name:
		anim.play(anim_name)


func _physics_process(delta: float) -> void:
	var horizontal_input := Input.get_axis("move_left", "move_right")

	# Move in ground and in air
	if horizontal_input != 0:
		velocity.x = horizontal_input * speed

		if horizontal_input > 0:
			target_rotation_y = deg_to_rad(90)
		else:
			target_rotation_y = deg_to_rad(-90)
	else:
		velocity.x = 0

	# Jump and handle animations bsaed on floor
	if is_on_floor():
		velocity.y = 0
		if Input.is_action_just_pressed("jump"):
			velocity.y = jump_velocity
			handle_animation(CharacterState.JUMPING)
		else:
			if horizontal_input == 0:
				handle_animation(CharacterState.IDLE)
				target_rotation_y = deg_to_rad(0)
			else:
				handle_animation(CharacterState.WALKING)
	else:
		velocity.y -= gravity * delta

	# Apply movement
	move_and_slide()

	# Reset if too low
	if position.y < -5:
		LevelManager.reset_player()

	# Smooth rotation
	rotation.y = lerp_angle(rotation.y, target_rotation_y, rotation_speed)

func _on_area_3d_area_entered(area: Area3D) -> void:
	if area.is_in_group("Hazard"):
		LevelManager.reset_player()
