extends CharacterBody2D
 
var coin_counter=0
@onready var coin_label= %Label

var tool_counter=0
@onready var tool_label= %Label2

const SPEED = 75.0
 


@onready var animated_sprite = $AnimatedSprite2D
 
func _physics_process(delta: float) -> void:

	# Get the input direction and handle horizontal movement

	var horizontal_direction := Input.get_axis("ui_left", "ui_right")

	if horizontal_direction:

		velocity.x = horizontal_direction * SPEED

	else:

		velocity.x = move_toward(velocity.x, 0, SPEED)
 
	# Handle vertical movement (up and down)

	var vertical_direction := Input.get_axis("ui_up", "ui_down")

	if vertical_direction:

		velocity.y = vertical_direction * SPEED

	else:

		velocity.y = move_toward(velocity.y, 0, SPEED)
 
	# Lógica de animações

	update_animations(horizontal_direction, vertical_direction)
 
	move_and_slide()
 
func update_animations(horizontal_direction: float, vertical_direction: float) -> void:

	# Hierarquia de animações baseada na direção

	if vertical_direction < 0:  # Cima

		animated_sprite.play("idle_up")

	elif vertical_direction > 0:  # Baixo

		animated_sprite.play("idle_down")

	elif horizontal_direction < 0:  # Esquerda

		animated_sprite.play("idle_left")

	elif horizontal_direction > 0:  # Direita

		animated_sprite.play("idle_right")
		#animated_sprite.play("idle_right")

	else:

		# Para cada direção, uma animação idle correspondente pode ser adicionada

		if animated_sprite.animation == "idle_up":

			animated_sprite.play("idle_up")

		elif animated_sprite.animation == "idle_down":

			animated_sprite.play("idle_down")

		elif animated_sprite.animation == "idle_left":

			animated_sprite.play("idle_left")

		elif animated_sprite.animation == "idle_right":

			animated_sprite.play("idle_right")

		else:

			animated_sprite.play("idle_down")  # Default idle
			


func _on_area_2d_area_entered(area: Area2D) -> void:
	if area.is_in_group("coin"):
		set_coin(coin_counter + 1)
		print(coin_counter)
	if area.is_in_group("tool"):
		set_tool(tool_counter + 1)
		print(tool_counter)
	if area.is_in_group("inimigo"):
		get_tree().change_scene_to_file("res://game.tscn")

func set_tool(new_tool_count: int) -> void:
	tool_counter=new_tool_count
	tool_label.text="Tools: "+str(tool_counter)
	
func set_coin(new_coin_count: int) -> void:
	coin_counter=new_coin_count
	coin_label.text="Coins: "+str(coin_counter)
	
 
