/* QueueUp.gg — app root: routing, state, tweaks */
const { useState, useEffect } = React;
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "twilight",
  "headingFont": "Space Grotesk",
  "glow": true,
  "memeCopy": true
}/*EDITMODE-END*/;

const FONT_STACK = {
  "Space Grotesk": "'Space Grotesk', system-ui, sans-serif",
  "Sora": "'Sora', system-ui, sans-serif",
  "Chakra Petch": "'Chakra Petch', system-ui, sans-serif",
  "Clash / DM": "'DM Sans', system-ui, sans-serif",
};

function newSessionId() { return Math.random().toString(36).slice(2, 8).toUpperCase(); }

/* GG monogram glyph — sits inside the theme-reactive .brand-mark gradient tile.
   Dark ink so it reads on every theme's tile. */
function GGMark({ s = 20 }) {
  return (
    <svg width={s} height={s} viewBox="0 0 64 64" fill="none" aria-hidden="true" style={{ display: "block" }}>
      <g fill="none" stroke="#0a0a12" strokeWidth="5.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M31 20a12 12 0 1 0 0 24 12 12 0 0 0 11-7.8" />
        <path d="M43 36.2H32.4" />
      </g>
      <circle cx="44" cy="22.4" r="3.1" fill="#0a0a12" />
    </svg>
  );
}

function Nav({ go, route }) {
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <div className="brand" onClick={() => go("home")}>
          <div className="brand-mark"><GGMark s={20} /></div>
          <div className="brand-name">GG<b>WhatNext</b></div>
        </div>
        <div className="nav-links">
          <button className={`nav-link hide-sm ${route === "about" ? "" : ""}`} onClick={() => go("about")}>About</button>
          <button className="btn btn-primary" style={{ padding: "9px 16px", fontSize: 14 }} onClick={() => go("wizard")}>
            {Icons.zap({ size: 16, fill: "currentColor", stroke: "none" })} Start Game Night
          </button>
        </div>
      </div>
    </nav>
  );
}

function About({ onStart }) {
  const future = [
    ["Discord bot", "Run /ggwhatnext right in your server — votes, results, the works."],
    ["Steam library sync", "Only recommend games the squad actually owns."],
    ["Group AI mode", "Natural-language 'what should we play?' with reasoning."],
    ["Friend compatibility", "See whose libraries and schedules line up best."],
    ["Trending feed", "What groups like yours are loading up this week."],
    ["Backlog analysis", "Finally beat that pile of shame, together."],
  ];
  return (
    <div className="container" style={{ padding: "60px 0 90px", maxWidth: 800 }}>
      <div className="kicker">About</div>
      <h1 style={{ fontSize: "clamp(30px,4.5vw,46px)", fontWeight: 700, margin: "10px 0 0", lineHeight: 1.05 }}>
        Game night shouldn't start with a 40-minute argument.
      </h1>
      <p className="muted" style={{ fontSize: 18, lineHeight: 1.6, marginTop: 20 }}>
        GGWhatNext is the tiebreaker. Instead of doom-scrolling everyone's libraries, you answer a few quick
        questions — who's online, what you're on, how long you've got, and the mood — and a transparent,
        rule-based engine returns picks that actually fit. No black box, no ads, no "trust me bro." Every
        recommendation shows exactly <i>why</i> it made the cut.
      </p>
      <div className="card" style={{ padding: 28, marginTop: 30 }}>
        <h3 style={{ fontSize: 20 }}>How the matching works</h3>
        <p className="muted" style={{ lineHeight: 1.6, marginTop: 12, marginBottom: 0 }}>
          First we <b style={{ color: "var(--text)" }}>filter</b> — a game has to fit your player count, run on
          a platform in the room, respect the free-only toggle, and fit your time window. Then we
          <b style={{ color: "var(--text)" }}> rank</b> what's left on mood overlap, player fit, session-length
          closeness, crossplay coverage, skill, and popularity as a tiebreaker. The top of the pile is your Best Match.
        </p>
      </div>
      <h3 style={{ fontSize: 20, marginTop: 40 }}>On the roadmap</h3>
      <div className="steps" style={{ gridTemplateColumns: "1fr 1fr", marginTop: 18 }}>
        {future.map(([t, d]) => (
          <div key={t} className="card step" style={{ padding: 20 }}>
            <h3 style={{ fontSize: 16, margin: 0 }}>{t} <span className="chip" style={{ marginLeft: 4 }}>soon</span></h3>
            <p style={{ marginTop: 8, fontSize: 14 }}>{d}</p>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 40 }}>
        <button className="btn btn-primary btn-lg" onClick={onStart}>{Icons.zap({ size: 19, fill: "currentColor", stroke: "none" })} Start Game Night</button>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState("home");
  const [prefs, setPrefs] = useState({
    players: 4, platforms: ["PC"], time: 60, moods: ["coop"],
    freeOnly: false, skill: "mixed", sessionId: newSessionId(), party: [],
  });
  const [results, setResults] = useState([]);

  // apply tweaks → CSS
  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", t.theme);
    root.style.setProperty("--display", FONT_STACK[t.headingFont] || FONT_STACK["Space Grotesk"]);
    root.style.setProperty("--glow-strength", t.glow ? "1" : "0");
  }, [t.theme, t.headingFont, t.glow]);

  const go = (r) => { setRoute(r); window.scrollTo({ top: 0 }); };

  const generate = () => {
    const res = window.recommend(prefs, window.GAMES);
    setResults(res);
    go("results");
  };
  const restart = () => {
    setPrefs((p) => ({ ...p, sessionId: newSessionId(), party: [] }));
    go("wizard");
  };

  // sample games for hero preview (a fun coop-ish default mix)
  const sample = React.useMemo(() => {
    const ids = ["lethal-company", "rocket-league", "stardew"];
    const ms = [96, 91, 88];
    return ids.map((id, i) => ({ ...window.GAMES.find((g) => g.id === id), _m: ms[i] }));
  }, []);

  return (
    <div className="shell">
      <div className="app-bg" />
      <Nav go={go} route={route} />
      <main style={{ flex: 1 }}>
        {route === "home" && <Home onStart={() => go("wizard")} onAbout={() => go("about")} sampleGames={sample} meme={t.memeCopy} />}
        {route === "about" && <About onStart={() => go("wizard")} />}
        {route === "wizard" && <Wizard prefs={prefs} setPrefs={setPrefs} onComplete={generate} onExit={() => go("home")} />}
        {route === "results" && <Results prefs={prefs} results={results} onRestart={restart} onTweak={() => go("wizard")} onVote={() => go("vote")} />}
        {route === "vote" && <VoteRoom prefs={prefs} results={results} onExit={() => go("results")} onRestart={restart} />}
      </main>

      <footer style={{ borderTop: "1px solid var(--border)", padding: "24px 0", marginTop: "auto" }}>
        <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
          <div className="brand" onClick={() => go("home")} style={{ opacity: .85 }}>
            <div className="brand-mark" style={{ width: 26, height: 26 }}><GGMark s={15} /></div>
            <span className="brand-name" style={{ fontSize: 15 }}>GG<b>WhatNext</b></span>
          </div>
          <div className="faint" style={{ fontFamily: "var(--mono)", fontSize: 12 }}>Rule-based MVP · {window.GAMES.length} games seeded · no login required</div>
        </div>
        <div className="container" style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 6 }}>
          <div className="faint" style={{ fontSize: 12, lineHeight: 1.5 }}>
            <b style={{ color: "var(--text-dim)" }}>Age Notice: 13+</b> — GGWhatNext is intended for users aged 13 and above.
          </div>
          <div className="faint" style={{ fontSize: 12, lineHeight: 1.5, maxWidth: 720 }}>
            Game ratings, descriptions, and classifications are provided by third-party sources and are not created or controlled by GGWhatNext.
          </div>
        </div>
      </footer>

      <TweaksPanel>
        <TweakSection label="Aesthetic direction" />
        <TweakRadio label="Theme" value={t.theme} options={["twilight", "synthwave", "acid", "ember", "mono"]} onChange={(v) => setTweak("theme", v)} />
        <TweakSelect label="Heading font" value={t.headingFont} options={Object.keys(FONT_STACK)} onChange={(v) => setTweak("headingFont", v)} />
        <TweakSection label="Style" />
        <TweakToggle label="Neon glow" value={t.glow} onChange={(v) => setTweak("glow", v)} />
        <TweakToggle label="Meme-y copy" value={t.memeCopy} onChange={(v) => setTweak("memeCopy", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
