extends PanelContainer

@export var practice_player: WorldPlayer

@onready var map_select: ItemList = %MapSelect

@onready var start_button: Button = %Start

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


func play_chime() -> void:
	game.sfx.chime.play()


func _ready() -> void:
	# Populate map selection
	for level: Level in Level.catalog.levels:
		map_select.add_item(level.level_name, level.preview)

	check_start_conditions()


## Close menu without starting game.
func cancel() -> void:
	queue_free()


## Start with the current game configuration.
func start() -> void:
	var manager := PracticeManager.new()
	manager.players = [practice_player]
	var level := selected_level()
	var init_world := func(world: World) -> void:
		world.manager = manager
		world.initial_level = level.scene
	game.queue_scene(World.SCENE).then(init_world)


## Returns the `Level` selected by the user if there is one, or `null` if no level is selected.
func selected_level() -> Level:
	var selections := map_select.get_selected_items()
	if selections:
		return Level.catalog.levels[selections[0]]
	return null


func _can_start() -> bool:
	return selected_level() != null


## Check if the game can be started with the current selection,
## and set the start button status appropriately.
func check_start_conditions() -> void:
	start_button.disabled = not _can_start()
