class_name CombatUI extends CanvasLayer

@onready var unit_panel: PanelContainer = %UnitPanel
@onready var name_label: Label = %NameLabel
@onready var hp_bar: ProgressBar = %HPBar

var _selected_unit: Unit

func _ready() -> void:
	unit_panel.visible = false
	for unit: Unit in get_tree().get_nodes_in_group("units"):
		unit.unit_selected_changed.connect(_on_unit_selected_changed)
	get_tree().node_added.connect(_on_node_added)

func _on_node_added(node: Node) -> void:
	if node is Unit and node.is_in_group("units"):
		node.unit_selected_changed.connect(_on_unit_selected_changed)

func _process(_delta: float) -> void:
	if _selected_unit:
		hp_bar.max_value = _selected_unit.current_stats.max_hp
		hp_bar.value = _selected_unit.current_stats.current_hp

func _on_unit_selected_changed(unit: Unit, selected: bool) -> void:
	if selected:
		_selected_unit = unit
		name_label.text = unit.current_info.name
		hp_bar.max_value = unit.current_stats.max_hp
		hp_bar.value = unit.current_stats.current_hp
		unit_panel.visible = true
	else:
		_selected_unit = null
		unit_panel.visible = false
