extends Control

enum GameState { MAIN_MENU, GAME, LOSS, WIN }
var current_game_state: GameState = GameState.MAIN_MENU

var main_menu_scene = preload("res://main_menu.tscn")
var game_scene = preload("res://main.tscn")
var score_screen_scene = preload("res://score_screen.tscn")

func _ready():
	$MainMenu.main_menu_interacted.connect(_on_main_menu_interacted)

func transition(new_state: GameState):
	# Clean up current scene

	if new_state == GameState.MAIN_MENU:
		var main_menu_instance = main_menu_scene.instantiate()
		add_child(main_menu_instance)
	elif new_state == GameState.GAME:
		var game_instance = game_scene.instantiate()
		add_child(game_instance)
		var manager = game_instance.get_node("%GameManager")
		manager.lost.connect(_on_loss)
		manager.won.connect(_on_win)
	elif new_state == GameState.LOSS:
		var score_screen_instance = score_screen_scene.instantiate()
		add_child(score_screen_instance)
		score_screen_instance.lose()
		score_screen_instance.restart_game.connect(_on_restart)
	elif new_state == GameState.WIN:
		var score_screen_instance = score_screen_scene.instantiate()
		add_child(score_screen_instance)
		score_screen_instance.win()
		score_screen_instance.restart_game.connect(_on_restart)

	# Clean up old scene
	match (current_game_state):
		GameState.MAIN_MENU:
			var main_menu_instance = $MainMenu
			main_menu_instance.queue_free()
		GameState.GAME:
			var main_instance = $Main
			main_instance.queue_free()
		GameState.LOSS:
			var score_screen_instance = $ScoreScreen
			score_screen_instance.queue_free()
		GameState.WIN:
			var score_screen_instance = $ScoreScreen
			score_screen_instance.queue_free()

	current_game_state = new_state

func _on_main_menu_interacted():
	transition(GameState.GAME)

func _on_loss():
	transition(GameState.LOSS)

func _on_win():
	transition(GameState.WIN)

func _on_restart():
	transition(GameState.GAME)
