extends Node

## GameController - Top-level controller managing menu and game states

enum State {
	MENU,
	PLAYING,
	PAUSED
}

var current_state: State = State.MENU

# Scene references
var main_menu: MainMenu = null
var game_scene: Node3D = null
var pause_menu: PauseMenu = null

# Preload the main game scene script
const MainScript = preload("res://scripts/Main.gd")

func _ready() -> void:
	process_mode = Node.PROCESS_MODE_ALWAYS
	_show_main_menu()

func _input(event: InputEvent) -> void:
	if event is InputEventKey and event.pressed:
		if event.keycode == KEY_ESCAPE:
			match current_state:
				State.PLAYING:
					_show_pause_menu()
				State.PAUSED:
					_hide_pause_menu()

func _show_main_menu() -> void:
	# Clean up any existing game
	if game_scene:
		game_scene.queue_free()
		game_scene = null

	if pause_menu:
		pause_menu.queue_free()
		pause_menu = null

	# Create main menu
	if not main_menu:
		main_menu = MainMenu.new()
		add_child(main_menu)
		main_menu.start_game.connect(_on_start_game)

	main_menu.visible = true
	current_state = State.MENU

func _on_start_game() -> void:
	# Hide menu
	if main_menu:
		main_menu.visible = false

	# Create game scene
	_start_new_game()

func _start_new_game() -> void:
	# Make sure game isn't paused
	get_tree().paused = false

	# Clean up existing game
	if game_scene:
		game_scene.queue_free()
		game_scene = null

	# Reset GameManager state
	if GameManager:
		GameManager.is_game_active = false
		GameManager.game_state = null

	# Create new game scene
	game_scene = Node3D.new()
	game_scene.set_script(MainScript)
	add_child(game_scene)

	# Create pause menu
	if not pause_menu:
		pause_menu = PauseMenu.new()
		add_child(pause_menu)
		pause_menu.resume_game.connect(_on_resume_game)
		pause_menu.restart_game.connect(_on_restart_game)
		pause_menu.return_to_menu.connect(_on_return_to_menu)

	current_state = State.PLAYING

func _show_pause_menu() -> void:
	if pause_menu:
		pause_menu.show_menu()
	current_state = State.PAUSED

func _hide_pause_menu() -> void:
	if pause_menu:
		pause_menu.hide_menu()
	current_state = State.PLAYING

func _on_resume_game() -> void:
	current_state = State.PLAYING

func _on_restart_game() -> void:
	_start_new_game()

func _on_return_to_menu() -> void:
	_show_main_menu()
