class_name TitleScreen extends Control

const SCENE := "res://src/ui/menus/title_screen/title_screen.tscn"

@export var title_crawl_scene: PackedScene
@export var settings_scene: PackedScene
@export var local_deathmatch_setup_scene: PackedScene
@export var practice_setup_scene: PackedScene

@onready var menu: Control = %Menu
@onready var settings_container: MarginContainer = %SettingsContainer
@onready var deathmatch_setup_container: MarginContainer = %DeathmatchSetupContainer
@onready var title_crawl_container: MarginContainer = %TitleCrawlContainer

@onready var state_machine: AnimationTree = $Menu/MenuStateMachine
@onready var menu_state: AnimationNodeStateMachinePlayback = state_machine["parameters/playback"]

@onready var idle_timer: Timer = %IdleTimer

@onready var game: Game = get_tree().get_first_node_in_group(Game.group)


func _ready() -> void:
	Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)


func play_chime() -> void:
	game.sfx.chime.play()


func start_title_crawl() -> void:
	var instance: Node = title_crawl_scene.instantiate()
	instance.tree_exiting.connect(idle_timer.start)
	title_crawl_container.add_child(instance)


func _input(event: InputEvent) -> void:
	if event is InputEventKey or event is InputEventJoypadButton or event is InputEventMouseButton:
		if menu_state.get_current_node() in ["press_start_fade_in", "press_start_idle"]:
			_to_main_menu()


func _unhide() -> void:
	menu.show()


func _hide() -> void:
	menu.hide()


func _to_main_menu() -> void:
	idle_timer.stop()
	menu_state.travel("main_idle")


func _to_single_player() -> void:
	menu_state.travel("single_player_idle")


func _to_multi_player() -> void:
	menu_state.travel("multi_player_idle")


func _to_local_multi() -> void:
	menu_state.travel("local_idle")


func _to_network_multi() -> void:
	menu_state.travel("network_idle")


func _on_quit() -> void:
	get_tree().root.propagate_notification(NOTIFICATION_WM_CLOSE_REQUEST)


func _open_settings() -> void:
	var instance: Control = settings_scene.instantiate()
	settings_container.add_child(instance)
	instance.tree_exited.connect(_unhide)
	_hide()


func _open_local_deathmatch_setup() -> void:
	var instance: Control = local_deathmatch_setup_scene.instantiate()
	deathmatch_setup_container.add_child(instance)
	instance.tree_exited.connect(_unhide)
	_hide()


func _open_practice_setup() -> void:
	var instance: Control = practice_setup_scene.instantiate()
	deathmatch_setup_container.add_child(instance)
	instance.tree_exited.connect(_unhide)
	_hide()
