class_name MainMenu
extends Node

const AMBIENCE_STREAM: AudioStream = preload("uid://cyxvsy5wjxhl7")

@onready var continue_button: Button = %ContinueButton
@onready var new_game_button: Button = %NewGameButton
@onready var quit_button: Button = %QuitButton
@onready var options_menu: Control = $OptionsMenu
@onready var main_menu_ui: Control = $MainMenuUI


func _ready() -> void:
	continue_button.disabled = not SaveManager.save_exists()
	(continue_button if not continue_button.disabled else new_game_button).grab_focus()

	AudioManager.play_audio(AMBIENCE_STREAM, AudioManager.AMBIENCE)


func _unhandled_input(event: InputEvent) -> void:
	if options_menu.is_visible_in_tree() and event.is_action_pressed(&"pause"):
		main_menu_ui.show()
		options_menu.hide()


func load_game() -> void:
	AudioManager.fade_audio(AMBIENCE_STREAM, -80.0, SceneFader.fade_in_duration, AudioManager.AMBIENCE, true)
	SceneFader.load_to_path(GameGlobals.GAME_PATH, GameGlobals.LEVELS.get(GameGlobals.level, &""))


func _on_new_game_button_pressed() -> void:
	if SceneFader.is_fading:
		return

	GameGlobals.reset_game()
	SaveManager.delete_save()
	SaveManager.save_game()
	load_game()


func _on_continue_button_pressed() -> void:
	if SceneFader.is_fading:
		return

	GameGlobals.reset_game()
	GameGlobals.load_from_save()
	load_game()


func _on_quit_button_pressed() -> void:
	if SceneFader.is_fading:
		return

	AudioManager.fade_audio(AMBIENCE_STREAM, -80.0, SceneFader.fade_out_duration, AudioManager.AMBIENCE)
	await SceneFader.fade_in()

	get_tree().quit()


func _on_settings_button_pressed() -> void:
	if SceneFader.is_fading:
		return

	main_menu_ui.hide()
	options_menu.show()


func _on_chase_button_pressed() -> void:
	if SceneFader.is_fading:
		return

	AudioManager.fade_audio(AMBIENCE_STREAM, -80.0, SceneFader.fade_out_duration, AudioManager.AMBIENCE, true)
	SceneFader.load_to_path("uid://d013wo01v8lr5")
