extends Control
class_name EscapeMenu
## Escape menu that opens when Escape is pressed
## Allows player to exit the game or resume playing

# Visibility
var is_visible: bool = false

# Player reference (to control mouse mode)
var player: Character = null

var _retire_button: Button = null

func _ready():
	# Start hidden
	hide()
	is_visible = false

	# Insert "Retire to Camp" between Resume and Exit - leave alive, bank everything
	var vbox = get_node_or_null("Panel/MarginContainer/VBoxContainer")
	var exit_button = get_node_or_null("Panel/MarginContainer/VBoxContainer/ExitButton")
	if vbox and exit_button:
		_retire_button = Button.new()
		_retire_button.name = "RetireButton"
		_retire_button.custom_minimum_size = Vector2(0, 50)
		_retire_button.add_theme_color_override("font_color", Color.WHITE)
		_retire_button.add_theme_color_override("font_hover_color", Color(1, 0.8, 0))
		_retire_button.add_theme_font_size_override("font_size", 20)
		_retire_button.pressed.connect(_on_retire_pressed)
		vbox.add_child(_retire_button)
		vbox.move_child(_retire_button, exit_button.get_index())

func _input(event):
	# Toggle on Escape press
	if event.is_action_pressed("quit"):
		toggle_menu()
		get_viewport().set_input_as_handled()

## Set the player reference
func set_player(p: Character):
	player = p

## Toggle menu visibility
func toggle_menu():
	is_visible = !is_visible
	if is_visible:
		show()
		_update_retire_button()
		# Release mouse when opening menu
		Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
	else:
		hide()
		# Recapture mouse when closing menu
		if player and player.is_multiplayer_authority():
			Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

## Retiring is only possible while alive with an active run
func _update_retire_button():
	if not _retire_button:
		return
	var can_retire = GameState.run_active and player and not player.is_dead
	_retire_button.visible = can_retire
	if can_retire:
		_retire_button.text = "Retire to Camp (+%dg)" % GameState.run_gold

## Called when Resume button is clicked
func _on_resume_pressed():
	toggle_menu()

## Walk out alive: bank all run gold, keep gear, return to the menu
func _on_retire_pressed():
	GameState.retire_run()

	multiplayer.multiplayer_peer = null
	Network.players.clear()

	if has_node("/root/HUD"):
		get_node("/root/HUD").reset()

	Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
	get_tree().reload_current_scene()

## Called when Exit button is clicked
func _on_exit_pressed():
	# Leaving alive still banks your winnings (GameState also catches window close)
	if GameState.run_active and player and not player.is_dead:
		GameState.retire_run()
	get_tree().quit()
