extends CanvasLayer

# HP bar, depth label, enemy count, death / win overlay.

@onready var hp_bar: ColorRect = $HPBar/Fill
@onready var hp_label: Label = $HPBar/Label
@onready var depth_label: Label = $InfoLabel
@onready var overlay: Control = $EndOverlay
@onready var overlay_title: Label = $EndOverlay/Title
@onready var overlay_hint: Label = $EndOverlay/Hint

const HP_COLOR_HIGH := Color(0.32, 0.82, 0.36)
const HP_COLOR_LOW  := Color(0.88, 0.28, 0.22)
const HP_BAR_MAX_WIDTH := 200.0

var _game_over := false
var _scene_ref: Node = null

func _ready() -> void:
	overlay.hide()
	_scene_ref = get_parent()
	_scene_ref.depth_changed.connect(_on_depth)
	_scene_ref.enemies_changed.connect(_on_enemies)
	_scene_ref.game_over.connect(_on_game_over)
	# Player is a sibling; @onready on parent isn't set yet when we fire.
	var p: Node = get_node("../Player")
	p.hp_changed.connect(_on_hp)

func _unhandled_input(event: InputEvent) -> void:
	if _game_over and event is InputEventKey and event.pressed and event.keycode == KEY_R:
		_game_over = false
		overlay.hide()
		_scene_ref.restart_from_start()

func _on_hp(current: int, maximum: int) -> void:
	var frac := 0.0 if maximum <= 0 else float(current) / float(maximum)
	hp_bar.size.x = HP_BAR_MAX_WIDTH * frac
	hp_bar.color = HP_COLOR_LOW.lerp(HP_COLOR_HIGH, frac)
	hp_label.text = "HP %d / %d" % [current, maximum]

func _on_depth(depth: int, total: int) -> void:
	depth_label.text = "Depth %d / %d" % [depth, total]

func _on_enemies(remaining: int, _total: int) -> void:
	depth_label.text = "%s     Enemies: %d" % [depth_label.text.split("  ")[0], remaining]

func _on_game_over(won: bool) -> void:
	_game_over = true
	overlay.show()
	if won:
		overlay_title.text = "YOU WIN"
		overlay_title.modulate = Color(0.35, 0.90, 0.45)
	else:
		overlay_title.text = "YOU DIED"
		overlay_title.modulate = Color(0.92, 0.28, 0.28)
	overlay_hint.text = "Press R to restart"
	Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
