extends CanvasLayer

var _score := 0
var _saved := 0
var _lost := false

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 _unhandled_input(event):
	if visible and _lost and event is InputEventKey and event.pressed and not event.echo and event.keycode == KEY_SPACE:
		get_viewport().set_input_as_handled()
		_on_restart_pressed()

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

func _on_game_lost(reason: String):
	$Center/Card/Margin/Column/Headline.text = reason
	_lost = true
	$Center/Card/Margin/Column/SpaceHint.visible = true
	_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)

	$Dim.color = Color(0.18, 0.05, 0.05, 1)

	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()
