extends CharacterBody3D

@export var move_speed: float = 5.0
@export var max_health: int = 10

@onready var anim: AnimationPlayer = $AnimationPlayer

@onready var hitbox: Area3D = $Area3D
@onready var restart_button: Button = $"../UI/RestartButton"
@onready var gameover_label: Label = $"../UI/GameOverLabel"
@onready var score_label: Label = $"../UI/ScoreLabel"
@onready var hp_label: Label = $"../UI/HPLabel"

@onready var rig: Node3D = $Rig

var health: int

var score: int = 0

# TODO 3


func _ready() -> void:
	health = max_health
	update_health_ui()
	# TODO 4
	

func _physics_process(_delta: float) -> void:
	# TODO 1
	
	
	var input_direction = Input.get_vector("left", "right", "up", "down")
	velocity.x = input_direction.x * move_speed
	velocity.z = input_direction.y * move_speed
	rig.rotation.y = atan2(input_direction.x, input_direction.y)
	move_and_slide()


func change_health(change: int):
	health += change
	health = clamp(health, 0, max_health)
	
	if health > max_health:
		health = max_health
	
	update_health_ui()
	
	if health <= 0:
		game_over_triggered()


func update_health_ui():
	hp_label.text = str(health) + "/" + str(max_health)


func game_over_triggered():
	visible = false
	move_speed = 0
	await get_tree().create_timer(0.5).timeout
	gameover_label.visible = true
	restart_button.visible = true


func _on_restart_button_pressed() -> void:
	print("Game reloaded!")
	get_tree().reload_current_scene()


func _on_score_timer_timeout() -> void:
	if health > 0:
		score += 1
		score_label.text = str(score)
