extends Node
class_name GameManager

@onready var overlay: CanvasLayer = %Overlay

static var health = 1
static var score = 0
var start_time: int = 0
var total_coins: int = 0

func _ready() -> void:
	get_tree().paused = false
	add_to_group("game_manager")
	start_time = Time.get_ticks_msec()
	_update_hearts()
	overlay.get_node("ScoreLabel").text = "Score: " + str(score)
	call_deferred("_count_coins")

func _update_hearts() -> void:
	overlay.get_node("Heart1").visible = health >= 1
	overlay.get_node("Heart2").visible = health >= 2
	overlay.get_node("Heart3").visible = health >= 3

func _count_coins() -> void:
	total_coins = get_tree().get_nodes_in_group("coin").size() + 2

func add_point():
	score += 1
	overlay.get_node("ScoreLabel").text = "Score: " + str(score)

func add_health():
	if health < 3:
		health += 1
		_update_hearts()

func take_damage(force_reload: bool = false):
	health -= 1
	if health <= 0:
		health = 1
		score = 0
		var player = get_tree().get_first_node_in_group("player")
		if player:
			player.die()
		await get_tree().create_timer(1.0).timeout
		get_tree().reload_current_scene()
	elif force_reload:
		score = 0
		_update_hearts()
		var player = get_tree().get_first_node_in_group("player")
		if player:
			player.die()
		await get_tree().create_timer(1.0).timeout
		get_tree().reload_current_scene()
	else:
		_update_hearts()
		get_tree().get_first_node_in_group("player").take_hit()

func show_end_screen() -> void:
	var elapsed = (Time.get_ticks_msec() - start_time) / 1000.0
	var end_screen = load("res://scenes/end_screen.tscn").instantiate()
	get_tree().root.add_child(end_screen)
	end_screen.setup(elapsed, score, total_coins)
	get_tree().paused = true
