/* global React, AppHeader, Btn, Eyebrow, Display, Field, FigureNum, Wordmark */
const { useState: useStateQP, useEffect: useEffectQP } = React;

function QuickPartyScreen({ theme, user, onClose, onLaunch, onNav, onLogout, onAdmin }) {
  const [topic, setTopic] = useStateQP("");
  const [tone, setTone] = useStateQP("speels");
  const [age, setAge] = useStateQP("");
  const [count, setCount] = useStateQP(15);
  const [autoAdvance, setAutoAdvance] = useStateQP(false);
  const [busy, setBusy] = useStateQP(false);
  const [error, setError] = useStateQP(null);
  const [elapsed, setElapsed] = useStateQP(0);

  const TONES = ["speels", "serieus", "sarcastisch", "leerrijk", "absurd"];
  const AGES = [
    { value: "", label: "Iedereen" },
    { value: "6-9", label: "6-9 jaar" },
    { value: "10-12", label: "10-12 jaar" },
    { value: "13-16", label: "13-16 jaar" },
    { value: "17-25", label: "17-25 jaar" },
    { value: "25+", label: "25+" },
  ];

  const RANDOM_TOPICS = [
    "Vlaamse muziek", "Wereldkeuken", "Sport in de jaren 90", "Disney-films",
    "Belgische politiek", "Dieren in Afrika", "De ruimte",
    "Videogames", "Geografie van Europa", "Beroemde schilderijen",
    "Wetenschap voor beginners", "Mythologie", "Belgische bieren",
    "Film quotes", "Natuur in Vlaanderen",
  ];

  const randomTopic = () => {
    setTopic(RANDOM_TOPICS[Math.floor(Math.random() * RANDOM_TOPICS.length)]);
  };

  const start = async () => {
    if (!topic.trim()) { setError("Kies een onderwerp."); return; }
    setBusy(true); setError(null); setElapsed(0);
    const started = Date.now();
    const tick = setInterval(() => setElapsed(Math.round((Date.now() - started) / 100) / 10), 100);
    try {
      const res = await window.kwistApi.post("/api/sessions/quick-party", {
        topic: topic.trim(),
        tone,
        age: age || null,
        questionCount: count,
        autoAdvance,
      });
      clearInterval(tick);
      // QPT-05: in autopilot openen we direct het projector-scherm — geen
      // host-app, niemand hoeft te klikken behalve één keer "Start" op de
      // projector zelf zodra de spelers gejoined zijn.
      if (autoAdvance) {
        window.location.href = `/projector?code=${encodeURIComponent(res.session.code)}`;
        return;
      }
      if (onLaunch) {
        onLaunch({
          id: res.quiz.id,
          title: res.quiz.title,
          category: res.quiz.category,
          questions: res.questions,
          color: res.quiz.color,
          code: res.session.code,
          sessionId: res.session.id,
          teamsEnabled: false,
        });
      }
    } catch (e) {
      clearInterval(tick);
      setError(e.data?.error || e.message || "Quick Party mislukt.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <AppHeader theme={theme} user={user} onLogout={onLogout} current="quick-party" onNav={onNav} onAdmin={onAdmin} />
      <main style={{ maxWidth: 720, margin: "0 auto", padding: "40px 32px 80px" }}>
        <section style={{ borderTop: `3px double ${theme.rule}`, padding: "32px 0 24px" }}>
          <Eyebrow theme={theme} style={{ color: theme.accent, marginBottom: 10 }}>── QUICK PARTY</Eyebrow>
          <Display theme={theme} size={64}>
            Kies een onderwerp,<br/><span style={{ color: theme.accent }}>wij doen de rest</span>.
          </Display>
          <p style={{ color: theme.fgDim, fontSize: 15, lineHeight: 1.55, marginTop: 16, maxWidth: 560 }}>
            AI genereert een quiz, er wordt direct een sessie geopend. Binnen 30 seconden speel je live. De quiz verdwijnt na 24 uur.
          </p>
        </section>

        <section style={{ marginTop: 32, display: "flex", flexDirection: "column", gap: 24 }}>
          <div>
            <Field theme={theme} label="Onderwerp" value={topic} onChange={setTopic} placeholder="Bijv. Belgische bieren, Disney-films, Sport..." autoFocus />
            <Btn theme={theme} variant="outline" size="sm" onClick={randomTopic} style={{ marginTop: 8 }}>
              Willekeurig onderwerp
            </Btn>
          </div>

          <div>
            <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── TOON</Eyebrow>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {TONES.map((t) => (
                <button key={t} onClick={() => setTone(t)} style={{
                  padding: "8px 16px",
                  background: tone === t ? theme.fg : "transparent",
                  color: tone === t ? theme.bg : theme.fg,
                  border: `1px solid ${tone === t ? theme.fg : theme.rule}`,
                  cursor: "pointer",
                  fontFamily: theme.fonts.display, fontSize: 15,
                  textTransform: "capitalize",
                }}>{t}</button>
              ))}
            </div>
          </div>

          <div>
            <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── LEEFTIJD DOELGROEP</Eyebrow>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {AGES.map((a) => (
                <button key={a.value} onClick={() => setAge(a.value)} style={{
                  padding: "8px 16px",
                  background: age === a.value ? theme.fg : "transparent",
                  color: age === a.value ? theme.bg : theme.fg,
                  border: `1px solid ${age === a.value ? theme.fg : theme.rule}`,
                  cursor: "pointer",
                  fontFamily: theme.fonts.display, fontSize: 15,
                }}>{a.label}</button>
              ))}
            </div>
          </div>

          <div>
            <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── AANTAL VRAGEN</Eyebrow>
            <div style={{ display: "flex", gap: 6 }}>
              {[10, 15, 20, 30].map((n) => (
                <button key={n} onClick={() => setCount(n)} style={{
                  padding: "8px 18px",
                  background: count === n ? theme.fg : "transparent",
                  color: count === n ? theme.bg : theme.fg,
                  border: `1px solid ${count === n ? theme.fg : theme.rule}`,
                  cursor: "pointer",
                  fontFamily: theme.fonts.display, fontSize: 18,
                }}>{n}</button>
              ))}
            </div>
          </div>

          <div>
            <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── HOSTLOZE MODUS</Eyebrow>
            <button onClick={() => setAutoAdvance((v) => !v)} style={{
              display: "flex", width: "100%", textAlign: "left",
              padding: "14px 18px",
              background: autoAdvance ? `${theme.accent}10` : "transparent",
              color: theme.fg,
              border: `2px solid ${autoAdvance ? theme.accent : theme.rule}`,
              cursor: "pointer", gap: 14, alignItems: "flex-start",
              fontFamily: theme.fonts.body,
            }}>
              <div style={{
                marginTop: 2, width: 22, height: 22, flexShrink: 0,
                border: `2px solid ${autoAdvance ? theme.accent : theme.rule}`,
                background: autoAdvance ? theme.accent : "transparent",
                display: "grid", placeItems: "center", color: "#fff",
                fontFamily: theme.fonts.display, fontSize: 14, fontWeight: 800,
              }}>{autoAdvance ? "✓" : ""}</div>
              <div>
                <div style={{ fontFamily: theme.fonts.display, fontSize: 18, marginBottom: 4 }}>
                  Autopilot — geen host nodig
                </div>
                <div style={{ fontSize: 13, color: theme.fgDim, lineHeight: 1.45 }}>
                  Alleen de projectorview is zichtbaar. De timer loopt vanzelf af, daarna verschijnt het juiste antwoord en de tussenstand, en de quiz gaat zelf naar de volgende vraag.
                </div>
              </div>
            </button>
          </div>

          {busy && (
            <GeneratingLoader theme={theme} elapsed={elapsed} topic={topic} />
          )}

          {error && !busy && (
            <div style={{ padding: "12px 16px", border: `1px solid ${theme.accent}`, background: `${theme.accent}10` }}>
              <Eyebrow theme={theme} style={{ color: theme.accent }}>{error}</Eyebrow>
            </div>
          )}

          <div style={{ borderTop: `1px solid ${theme.rule}`, paddingTop: 24, display: "flex", gap: 12, alignItems: "center" }}>
            <Btn theme={theme} size="lg" onClick={start} disabled={busy} style={{ opacity: busy ? 0.6 : 1 }}>
              {busy ? "Bezig met genereren..." : "Start Quick Party →"}
            </Btn>
            <Btn theme={theme} variant="outline" onClick={onClose}>Annuleren</Btn>
          </div>
        </section>
      </main>
    </div>
  );
}

window.QuickPartyScreen = QuickPartyScreen;
