class_name TitleScreen
extends Control

@onready var _start_game_button: Button = $Options/StartGameButton
@onready var _options_button: Button = $Options/OptionsButton
@onready var _credits_button: Button = $Options/CreditsButton
@onready var _exit_button: Button = $Options/ExitButton
@onready var _background: ColorRect = $FadeOut

func _ready() -> void:
	_start_game_button.pressed.connect(_on_start_game_pressed)
	_options_button.pressed.connect(_on_options_pressed)
	_credits_button.pressed.connect(_on_credit_pressed)
	_exit_button.pressed.connect(_on_exit_pressed)
	_start_game_button.grab_focus()
	
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 _on_start_game_pressed() -> void:
	# Fade out
	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()")
		
	
	SceneManager.change_scene("res://scenes/components/intro.tscn")

func _on_options_pressed() -> void:
	print('Options Pressed')

func _on_credit_pressed() -> void:
	print('Credit Pressed')

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