extends CanvasLayer

var _score := 0
var _saved := 0

func _ready():
	visible = false
	EventBus.game_won.connect(_on_game_won)
	EventBus.game_lost.connect(_on_game_lost)
	EventBus.score_changed.connect(func(s): _score = s)
	EventBus.saved_changed.connect(func(s): _saved = s)
	$Center/Card/Margin/Column/RestartButton.pressed.connect(_on_restart_pressed)

func _on_game_won():
	$Center/Card/Margin/Column/Headline.text = "YOU ESCAPED"
	_show()

func _on_game_lost():
	$Center/Card/Margin/Column/Headline.text = "TOO FEW"
	_apply_loss_palette()
	_show()

func _apply_loss_palette():
	var border := Color(1, 0.3, 0.3, 1)
	var subtle := Color(0.95, 0.7, 0.7, 1)

	var card_style := ($Center/Card.get_theme_stylebox("panel") as StyleBoxFlat).duplicate() as StyleBoxFlat
	if card_style:
		card_style.border_color = border
		card_style.bg_color = Color(0.18, 0.05, 0.05, 1)
		$Center/Card.add_theme_stylebox_override("panel", card_style)

	var button = $Center/Card/Margin/Column/RestartButton
	var button_style := (button.get_theme_stylebox("normal") as StyleBoxFlat).duplicate() as StyleBoxFlat
	if button_style:
		button_style.border_color = border
		button_style.bg_color = Color(0.3, 0.1, 0.1, 1)
		for state in ["normal", "hover", "pressed", "focus"]:
			button.add_theme_stylebox_override(state, button_style)
	button.add_theme_color_override("font_color", border)

	$Center/Card/Margin/Column/Headline.add_theme_color_override("font_color", border)
	$Center/Card/Margin/Column/ScoreLabel.add_theme_color_override("font_color", subtle)
	$Center/Card/Margin/Column/SavedLabel.add_theme_color_override("font_color", subtle)

func _show():
	$Center/Card/Margin/Column/ScoreLabel.text = "Score: %d" % _score
	$Center/Card/Margin/Column/SavedLabel.text = "Survivors saved: %d" % _saved
	visible = true

func _on_restart_pressed():
	get_tree().reload_current_scene()
