extends CharacterBody3D

@export var move_speed: float = 6.0
@export var jump_velocity: float = 4.5
@export var mouse_sensitivity: float = 0.002

@export var gravity: float = 9.8

@onready var head: Node3D = $Head
@onready var camera: Camera3D = $Head/Camera3D

@export var fade_out: Area3D

var pitch := 0.0

# --- Footstep Settings ---
@export var footstep_sounds: Array[String] = [
	"res://audio/footsteps/0.ogg",
	"res://audio/footsteps/1.ogg",
	"res://audio/footsteps/2.ogg",
	"res://audio/footsteps/3.ogg",
	"res://audio/footsteps/4.ogg",
	"res://audio/footsteps/5.ogg",
	"res://audio/footsteps/6.ogg",
	"res://audio/footsteps/7.ogg",
	"res://audio/footsteps/8.ogg"
]

@export var footstep_interval: float = 0.5

var footstep_timer: float = 0.0

func _ready():
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	randomize()


func _input(event):
	if fade_out and fade_out.get_node("FadeUI").ending_active:
		return
	
	if event is InputEventMouseMotion:
		# Yaw (left/right)
		rotate_y(-event.relative.x * mouse_sensitivity)

		# Pitch (up/down)
		pitch -= event.relative.y * mouse_sensitivity
		pitch = clamp(pitch, deg_to_rad(-89), deg_to_rad(89))
		head.rotation.x = pitch

	if event.is_action_pressed("ui_cancel"):
		Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)


func _physics_process(delta):
	
	if fade_out and fade_out.get_node("FadeUI").ending_active:
		return
	
	# Gravity
	if not is_on_floor():
		velocity.y -= gravity * delta

	# Jump
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = jump_velocity

	# Movement input
	var input_dir = Vector2(
		Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
		Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")
	)

	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()

	if direction:
		velocity.x = direction.x * move_speed
		velocity.z = direction.z * move_speed
	else:
		velocity.x = move_toward(velocity.x, 0, move_speed)
		velocity.z = move_toward(velocity.z, 0, move_speed)

	move_and_slide()
	_handle_footsteps(delta)

func _handle_footsteps(delta: float) -> void:
	var horizontal_speed = Vector2(velocity.x, velocity.z).length()

	if is_on_floor() and horizontal_speed > 0.1:
		footstep_timer -= delta

		if footstep_timer <= 0.0:
			_play_random_footstep()
			footstep_timer = footstep_interval
	else:
		footstep_timer = 0.0


func _play_random_footstep() -> void:
	if footstep_sounds.is_empty():
		return

	var sound_path = footstep_sounds[randi() % footstep_sounds.size()]
	AudioManager.play(sound_path, -5.0)
