extends Control
## Menu shown in-game when the user presses pause.

@export var settings_scene: PackedScene

var _freeze_input := false

@onready var menu_list: VBoxContainer = %MenuList
@onready var quit_confirm: CenterContainer = %QuitConfirm
@onready var end_game_confirm: CenterContainer = %EndGameConfirm
@onready var settings_container: MarginContainer = %SettingsContainer

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


func _ready() -> void:
	Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
	Engine.time_scale = 1.0


func _unhandled_key_input(event: InputEvent) -> void:
	if not _freeze_input and event.is_action_pressed("pause"):
		get_viewport().set_input_as_handled()
		resume()


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


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


func resume() -> void:
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	queue_free()


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


func quit() -> void:
	quit_confirm.show()


func cancel_quit() -> void:
	quit_confirm.hide()


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


func end_game() -> void:
	end_game_confirm.show()


func cancel_end_game() -> void:
	end_game_confirm.hide()


func confirm_end_game() -> void:
	world.fade_to_title()
