package thb.jeanluc.adventure.menu;

import thb.jeanluc.adventure.io.GameIO;
import thb.jeanluc.adventure.save.SaveService;
import thb.jeanluc.adventure.save.SaveSlotInfo;

import java.util.ArrayList;
import java.util.List;

/** Frontend-agnostic main menu, slot picker, and new-game name prompt. */
public final class MainMenu {

    private MainMenu() {
    }

    /** Shows the main menu and returns the chosen action. */
    public static MenuAction show(GameIO io) {
        int i = io.choose("HAUNTED MANOR",
                List.of("New Game", "Load Game", "Settings", "Quit"));
        return MenuAction.values()[i];
    }

    /** Prompts for a new save name; blank input yields {@code defaultName}. */
    public static String promptName(GameIO io, String defaultName) {
        io.write("Name your save (Enter for \"" + defaultName + "\"):");
        String line = io.readLine();
        return (line == null || line.isBlank()) ? defaultName : line.trim();
    }

    /**
     * Lets the player pick a save slot to load. Returns the chosen
     * {@link SaveSlotInfo}, or {@code null} if there are none or the player
     * picks "Back".
     */
    public static SaveSlotInfo pickSlot(GameIO io, SaveService saves) {
        List<SaveSlotInfo> slots = saves.list();
        if (slots.isEmpty()) {
            io.write("No saved games.");
            return null;
        }
        List<String> labels = new ArrayList<>();
        for (SaveSlotInfo s : slots) {
            labels.add(s.slotName() + "  (" + s.roomId() + ", turn " + s.turn() + ")");
        }
        labels.add("Back");
        int i = io.choose("LOAD GAME", labels);
        return i < slots.size() ? slots.get(i) : null;
    }
}
