class_name PlayerHUD
extends CanvasLayer

const HEART_SCENE: PackedScene = preload("res://scenes/ui/heart.tscn")
const HEALTH_PER_HEART: int = 4

@onready var _hearts_container: HBoxContainer = $MarginContainer/HeartsContainer

var _hearts: Array[Heart] = []

func _ready() -> void:
	EventBus.player_health_changed.connect(_on_player_health_changed)

func _on_player_health_changed(current_health: int, max_health: int) -> void:
	var heart_count: int = ceili(float(max_health) / HEALTH_PER_HEART)
	if heart_count != _hearts.size():
		_build_hearts(heart_count)

	for i in _hearts.size():
		var remaining: int = clampi(current_health - i * HEALTH_PER_HEART, 0, HEALTH_PER_HEART)
		_hearts[i].set_value(remaining)

func _build_hearts(heart_count: int) -> void:
	for heart in _hearts:
		heart.queue_free()
	_hearts.clear()

	for i in heart_count:
		var heart: Heart = HEART_SCENE.instantiate()
		_hearts_container.add_child(heart)
		_hearts.append(heart)
