class_name DeathScreen
extends Control

const GAME_OVER_DELAY: float = 0.3
const VILLAGE_DESTROYED_DELAY: float = 0.7
const OPTIONS_DELAY: float = 1.5

@onready var _death_sprite: AnimatedSprite2D = $PlayerDeathSprite
@onready var _game_over_label: Label = $TextLayer/GameOverLabel
@onready var _village_destroyed_label: Label = $TextLayer/VillageDestroyedLabel
@onready var _options_container: HBoxContainer = $OptionsContainer
@onready var _continue_button: Button = $OptionsContainer/ContinueButton
@onready var _title_screen_button: Button = $OptionsContainer/TitleScreenButton
@onready var _exit_button: Button = $OptionsContainer/ExitButton
@onready var _background: ColorRect = $FadeOut

func _ready() -> void:
	_reset_sequence()
	_continue_button.pressed.connect(_on_continue_pressed)
	_title_screen_button.pressed.connect(_on_title_screen_pressed)
	_exit_button.pressed.connect(_on_exit_pressed)
	_play_sequence()

func _unhandled_input(event: InputEvent) -> void:
	if not event.is_action_pressed("interact"):
		return
	var viewport: Viewport = get_viewport()
	if viewport == null:
		return
	var focused: Control = viewport.gui_get_focus_owner()
	if focused is Button:
		(focused as Button).pressed.emit()
		viewport.set_input_as_handled()

func _play_sequence() -> void:
	_death_sprite.flip_h = EventBus.last_death_facing_direction < 0.0
	_death_sprite.play("player_death")
	await _death_sprite.animation_finished
	await get_tree().create_timer(GAME_OVER_DELAY).timeout
	_game_over_label.visible = true
	AudioManager.play_sfx("game_over")
	await get_tree().create_timer(VILLAGE_DESTROYED_DELAY).timeout
	_village_destroyed_label.visible = true
	await get_tree().create_timer(OPTIONS_DELAY).timeout
	_options_container.visible = true
	_continue_button.grab_focus()

func _reset_sequence() -> void:
	_game_over_label.visible = false
	_village_destroyed_label.visible = false
	_options_container.visible = false

func _on_continue_pressed() -> void:
	await _fade_out()
	SceneManager.change_scene(EventBus.last_level_path)

func _on_title_screen_pressed() -> void:
	await _fade_out()
	SceneManager.change_scene("res://scenes/components/title_screen.tscn")

func _on_exit_pressed() -> void:
	SceneManager.quit_game()

func _fade_out() -> void:
	var tween: Tween = create_tween()
	tween.tween_property(_background, "color:a", 1.0, 1.2)
	await tween.finished
	if OS.get_name() == "Web":
		JavaScriptBridge.eval("document.querySelector('canvas').focus()")
