/* global React, Btn, Eyebrow, Display, Rule, FigureNum, Field, Wordmark */
const { useState: useStateWiz, useEffect: useEffectWiz } = React;

function WizardScreen({ theme, onClose, onLaunch }) {
  const [step, setStep] = useStateWiz(0);
  const [data, setData] = useStateWiz({
    topic: "",
    description: "",
    audience: "vrienden",
    age: "",
    difficulty: "gemiddeld",
    questionCount: 15,
    types: ["mc", "tf"],
    tone: "speels",
    timer: 20,
    teams: false,
    title: "",
    sourceText: "",
    sourceLabel: "",
  });
  const [launching, setLaunching] = useStateWiz(false);
  const [launchError, setLaunchError] = useStateWiz(null);

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const launch = async () => {
    if (launching) return;
    if (!data.generated || !data.generated.questions?.length) {
      setLaunchError("Wacht tot de AI klaar is met genereren.");
      return;
    }
    setLaunching(true);
    setLaunchError(null);
    try {
      const api = window.kwistApi;
      const quizPayload = {
        title: data.title || data.generated.title || data.topic,
        subtitle: data.generated.subtitle || null,
        category: data.generated.category || "AI gegenereerd",
        type: data.tone === "speels" ? "party" : "serieus",
        color: theme.accent,
        glyph: "✦",
        author: null,
        settings: {
          audience: data.audience,
          difficulty: data.difficulty,
          tone: data.tone,
          timer: data.timer,
          teams: data.teams,
        },
        questions: data.generated.questions.map((q, i) => ({
          type: q.type || "mc",
          prompt: q.prompt,
          options: q.options || null,
          answer: q.answer || null,
          timeLimit: q.timeLimit ?? data.timer ?? 20,
        })),
      };
      const quizRes = await api.post("/api/quizzes", quizPayload);
      // Nieuwe quizzes komen als concept binnen — eerst publiceren, dan sessie.
      const pubRes = await api.post(`/api/quizzes/${quizRes.quiz.id}/publish`, {});
      const sessionRes = await api.post("/api/sessions", {
        quizId: quizRes.quiz.id,
        teams: data.teams,
      });
      onLaunch({
        id: quizRes.quiz.id,
        title: pubRes.quiz.title,
        subtitle: pubRes.quiz.subtitle,
        category: pubRes.quiz.category,
        questions: quizPayload.questions.length,
        plays: 0,
        type: pubRes.quiz.type,
        color: pubRes.quiz.color,
        glyph: pubRes.quiz.glyph || "✦",
        code: sessionRes.session.code,
        sessionId: sessionRes.session.id,
        teamsEnabled: !!data.teams,
      });
    } catch (e) {
      setLaunchError(e.message || "Sessie kon niet starten");
    } finally {
      setLaunching(false);
    }
  };

  const steps = [
    { num: "I", label: "Onderwerp", roman: "Hoofdstuk Ⅰ" },
    { num: "II", label: "Stijl", roman: "Hoofdstuk Ⅱ" },
    { num: "III", label: "Vragen", roman: "Hoofdstuk Ⅲ" },
    { num: "IV", label: "Preview", roman: "Hoofdstuk Ⅳ" },
    { num: "V", label: "Bewerken", roman: "Hoofdstuk Ⅴ" },
  ];

  const next = () => setStep(Math.min(steps.length - 1, step + 1));
  const prev = () => setStep(Math.max(0, step - 1));

  return (
    <div style={{ minHeight: "100vh", background: theme.bg, display: "flex", flexDirection: "column" }}>
      {/* HEADER */}
      <header style={{ borderBottom: `1px solid ${theme.rule}`, padding: "16px 40px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <button onClick={onClose} style={{
            background: "transparent", border: "none",
            fontFamily: theme.fonts.display, fontSize: 16, color: theme.fg, cursor: "pointer",
          }}>← terug naar dashboard</button>
          <div style={{ width: 1, height: 16, background: theme.rule }} />
          <Wordmark size={70} />
        </div>
        <Eyebrow theme={theme}>NIEUWE QUIZ · MET HULP VAN AI · AUTOSAVE AAN</Eyebrow>
      </header>

      {/* PROGRESS — newspaper-style */}
      <div style={{ borderBottom: `3px double ${theme.rule}`, background: theme.bg }}>
        <div style={{ maxWidth: 1320, margin: "0 auto", padding: "20px 40px", display: "grid", gridTemplateColumns: `repeat(${steps.length}, 1fr)`, gap: 0 }}>
          {steps.map((s, i) => {
            const active = i === step;
            const done = i < step;
            return (
              <div key={s.num} onClick={() => setStep(i)} style={{
                cursor: "pointer",
                padding: "0 24px",
                borderRight: i < steps.length - 1 ? `1px dashed ${theme.rule}` : "none",
                display: "flex",
                alignItems: "center",
                gap: 14,
              }}>
                <FigureNum theme={theme} size={48} accent={active}>
                  {done ? "✓" : s.num}
                </FigureNum>
                <div>
                  <Eyebrow theme={theme} style={{ color: active ? theme.accent : theme.fgDim }}>{s.roman}</Eyebrow>
                  <div style={{
                    fontFamily: theme.fonts.display,
                    fontSize: 22,
                    color: active ? theme.fg : (done ? theme.fgDim : theme.fg),
                    opacity: !done && !active ? 0.5 : 1,
                  }}>{s.label}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* CONTENT */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1.4fr 1fr", maxWidth: 1320, margin: "0 auto", width: "100%" }}>
        <div style={{ padding: "44px 56px 44px 40px", borderRight: `1px solid ${theme.rule}`, overflowY: "auto" }}>
          {step === 0 && <Step1 theme={theme} data={data} update={update} />}
          {step === 1 && <Step2 theme={theme} data={data} update={update} />}
          {step === 2 && <Step3 theme={theme} data={data} update={update} />}
          {step === 3 && <Step4 theme={theme} data={data} update={update} />}
          {step === 4 && <Step5 theme={theme} data={data} update={update} onBack={() => setStep(3)} />}
        </div>
        <PreviewPane theme={theme} data={data} step={step} />
      </div>

      {/* FOOTER */}
      <footer style={{
        borderTop: `1px solid ${theme.rule}`,
        padding: "16px 40px",
        background: theme.bg,
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
      }}>
        <Eyebrow theme={theme}>
          HOOFDSTUK {step + 1} / {steps.length}
          {launchError ? <span style={{ color: theme.accent, marginLeft: 12 }}>· {launchError}</span> : null}
        </Eyebrow>
        <div style={{ display: "flex", gap: 10 }}>
          {step > 0 && <Btn theme={theme} variant="outline" onClick={prev}>← Vorige</Btn>}
          {step < steps.length - 1 ? (
            <Btn theme={theme} onClick={next}>Volgende →</Btn>
          ) : (
            <Btn theme={theme} size="lg" onClick={launch} disabled={launching || !data.generated} style={{ opacity: (launching || !data.generated) ? 0.6 : 1 }}>
              {launching ? "Sessie aanmaken…" : "Genereer & start de sessie"} <span style={{ fontFamily: theme.fonts.display, }}>→</span>
            </Btn>
          )}
        </div>
      </footer>
    </div>
  );
}

// AIW-04: bron-keuze (PDF/URL/TXT). PDF is voorlopig disabled — backend
// support komt later (vereist pdf-parse). URL en TXT werken via /api/ai/ingest.
function BronPicker({ theme, data, update }) {
  const [mode, setMode] = useStateWiz(null); // "url" | "text" | null
  const [busy, setBusy] = useStateWiz(false);
  const [err, setErr] = useStateWiz(null);
  const [urlVal, setUrlVal] = useStateWiz("");
  const [textVal, setTextVal] = useStateWiz("");

  const submit = async (type) => {
    setErr(null);
    setBusy(true);
    try {
      const payload = type === "url" ? { type, url: urlVal } : { type, text: textVal };
      const res = await window.kwistApi.post("/api/ai/ingest", payload);
      update("sourceText", res.text);
      update("sourceLabel", type === "url" ? res.url : `eigen tekst — ${res.chars.toLocaleString()} tekens`);
      setMode(null);
      setUrlVal(""); setTextVal("");
    } catch (e) {
      setErr(e.data?.error || e.message || "Fout bij verwerken");
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0, border: `1px solid ${theme.rule}` }}>
        {[
          { k: "pdf", i: "PDF", l: "Document", disabled: true, hint: "Binnenkort" },
          { k: "url", i: "URL", l: "Webpagina" },
          { k: "text", i: "TXT", l: "Eigen tekst" },
        ].map((s, i) => (
          <button key={s.k} disabled={s.disabled}
            onClick={() => !s.disabled && setMode(s.k)}
            style={{
              background: mode === s.k ? theme.bg2 : "transparent",
              color: s.disabled ? theme.fgDim : theme.fg,
              border: "none", borderRight: i < 2 ? `1px solid ${theme.rule}` : "none",
              padding: "20px 16px", textAlign: "left",
              cursor: s.disabled ? "not-allowed" : "pointer",
              opacity: s.disabled ? 0.5 : 1,
              transition: "background .15s",
            }}
            onMouseEnter={(e) => !s.disabled && (e.currentTarget.style.background = theme.bg2)}
            onMouseLeave={(e) => !s.disabled && mode !== s.k && (e.currentTarget.style.background = "transparent")}>
            <FigureNum theme={theme} size={28}>{s.i}</FigureNum>
            <div style={{ fontFamily: theme.fonts.display, fontSize: 17, marginTop: 4 }}>{s.l}</div>
            {s.hint && <div style={{ fontFamily: theme.fonts.body, fontSize: 11, color: theme.fgDim, marginTop: 2 }}>{s.hint}</div>}
          </button>
        ))}
      </div>

      {mode === "url" && (
        <div style={{ marginTop: 14, padding: 16, border: `1px solid ${theme.rule}`, background: theme.bg2 }}>
          <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── Webpagina-URL</Eyebrow>
          <input value={urlVal} onChange={(e) => setUrlVal(e.target.value)}
            placeholder="https://nl.wikipedia.org/wiki/..." autoFocus
            style={{ width: "100%", background: "transparent", color: theme.fg, border: "none", borderBottom: `1px solid ${theme.rule}`, padding: "8px 0", fontFamily: theme.fonts.body, fontSize: 16, outline: "none" }} />
          {err && <div style={{ marginTop: 10, color: theme.signal, fontSize: 13 }}>{err}</div>}
          <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
            <Btn theme={theme} size="sm" onClick={() => submit("url")} disabled={!urlVal || busy}>{busy ? "Ophalen…" : "Ophalen →"}</Btn>
            <Btn theme={theme} size="sm" variant="outline" onClick={() => { setMode(null); setErr(null); }}>Annuleer</Btn>
          </div>
        </div>
      )}

      {mode === "text" && (
        <div style={{ marginTop: 14, padding: 16, border: `1px solid ${theme.rule}`, background: theme.bg2 }}>
          <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── Plak je eigen tekst</Eyebrow>
          <textarea value={textVal} onChange={(e) => setTextVal(e.target.value)}
            rows={8} placeholder="Plak hier de tekst (notities, hoofdstukken, transcript…) waar de AI vragen uit moet halen."
            style={{ width: "100%", background: theme.bg, color: theme.fg, border: `1px solid ${theme.rule}`, padding: "10px 12px", fontFamily: theme.fonts.body, fontSize: 14, outline: "none", resize: "vertical", lineHeight: 1.5 }} />
          {err && <div style={{ marginTop: 10, color: theme.signal, fontSize: 13 }}>{err}</div>}
          <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
            <Btn theme={theme} size="sm" onClick={() => submit("text")} disabled={!textVal.trim() || busy}>{busy ? "Verwerken…" : "Gebruik tekst →"}</Btn>
            <Btn theme={theme} size="sm" variant="outline" onClick={() => { setMode(null); setErr(null); }}>Annuleer</Btn>
          </div>
        </div>
      )}
    </>
  );
}

// ===== STEPS =====
function StepHeader({ theme, eyebrow, title, intro }) {
  return (
    <div style={{ marginBottom: 32 }}>
      <Eyebrow theme={theme} style={{ color: theme.accent, marginBottom: 10 }}>── {eyebrow}</Eyebrow>
      <Display theme={theme} size={56} style={{ marginBottom: 14 }}>{title}</Display>
      {intro && <p style={{ fontSize: 16, color: theme.fgDim, lineHeight: 1.55, margin: 0, maxWidth: 540 }}>{intro}</p>}
    </div>
  );
}

function Step1({ theme, data, update }) {
  const suggestions = [
    "Algemene kennis",
    "Wetenschap & natuur",
    "Geschiedenis",
    "Sport",
    "Film & muziek",
    "Eten & drinken",
  ];
  return (
    <div>
      <StepHeader theme={theme} eyebrow="Hoofdstuk I"
        title={<>Waar gaat<br/>de quiz <span style={{ }}>over</span>?</>}
        intro="Hoe specifieker, hoe beter de vragen worden. Een tekst plakken of een link werkt ook."
      />

      <Eyebrow theme={theme} style={{ marginBottom: 8 }}>Onderwerp</Eyebrow>
      <textarea
        value={data.topic}
        onChange={(e) => update("topic", e.target.value)}
        rows={3}
        style={{
          width: "100%", background: "transparent", color: theme.fg,
          border: "none", borderBottom: `1px solid ${theme.rule}`,
          padding: "10px 0",
          fontFamily: theme.fonts.display, fontSize: 28,
          outline: "none", resize: "vertical", lineHeight: 1.2,
          letterSpacing: "-0.01em",
        }}
        placeholder="Bv. 'Jaren 90 hits', 'Onboarding sales team' of plak een tekst/link."
      />

      <Eyebrow theme={theme} style={{ display: "block", marginTop: 28, marginBottom: 10 }}>── Suggesties uit de redactie</Eyebrow>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
        {suggestions.map((s) => (
          <button key={s} onClick={() => update("topic", s)} style={{
            background: data.topic === s ? theme.fg : "transparent",
            color: data.topic === s ? theme.bg : theme.fg,
            border: `1px solid ${data.topic === s ? theme.fg : theme.rule}`,
            borderRadius: 999,
            padding: "7px 14px",
            fontFamily: theme.fonts.body, fontSize: 13,
            cursor: "pointer", transition: "all .15s",
          }}>{s}</button>
        ))}
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginTop: 32, marginBottom: 10 }}>── Of upload een bron</Eyebrow>
      <BronPicker theme={theme} data={data} update={update} />
      {data.sourceText && (
        <div style={{
          marginTop: 12, padding: "10px 14px",
          border: `1px solid ${theme.rule}`,
          background: theme.bg2,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontFamily: theme.fonts.body, fontSize: 13,
        }}>
          <span>
            <strong style={{ fontFamily: theme.fonts.display }}>Bron geladen ·</strong> {data.sourceLabel || "tekst"}
            <span style={{ color: theme.fgDim, marginLeft: 8 }}>({data.sourceText.length.toLocaleString()} tekens)</span>
          </span>
          <button onClick={() => { update("sourceText", ""); update("sourceLabel", ""); }}
            style={{ background: "transparent", border: `1px solid ${theme.rule}`, padding: "4px 10px", cursor: "pointer", fontFamily: theme.fonts.body, fontSize: 12, color: theme.fg }}>
            wissen
          </button>
        </div>
      )}

      <div style={{ marginTop: 28 }}>
        <Field theme={theme} label="── Extra context (optioneel)" value={data.description} onChange={(v) => update("description", v)} placeholder="Bv. 'Geen vragen over Marco Borsato'" />
      </div>
    </div>
  );
}

function Step2({ theme, data, update }) {
  return (
    <div>
      <StepHeader theme={theme} eyebrow="Hoofdstuk II"
        title={<>Voor wie<br/>en hoe <span style={{ }}>pittig</span>?</>}
        intro="Bepaalt de toon, de moeilijkheid, en hoe spelers het ervaren."
      />

      <Eyebrow theme={theme} style={{ display: "block", marginBottom: 10 }}>── Doelgroep</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 32 }}>
        {[
          { v: "vrienden", l: "Vrienden", d: "Informeel, met humor" },
          { v: "collegas", l: "Collega's", d: "Werk-context" },
          { v: "familie", l: "Familie", d: "Voor jong en oud" },
        ].map((o) => (
          <Choice key={o.v} theme={theme} active={data.audience === o.v} onClick={() => update("audience", o.v)}
            title={o.l} subtitle={o.d} />
        ))}
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginBottom: 10 }}>── Leeftijd doelgroep</Eyebrow>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 32 }}>
        {[
          { v: "", l: "Iedereen" },
          { v: "6-9", l: "6-9 jaar" },
          { v: "10-12", l: "10-12 jaar" },
          { v: "13-16", l: "13-16 jaar" },
          { v: "17-25", l: "17-25 jaar" },
          { v: "25+", l: "25+" },
        ].map((o) => (
          <button key={o.v} onClick={() => update("age", o.v)} style={{
            padding: "8px 16px",
            background: data.age === o.v ? theme.fg : "transparent",
            color: data.age === o.v ? theme.bg : theme.fg,
            border: `1px solid ${data.age === o.v ? theme.fg : theme.rule}`,
            cursor: "pointer",
            fontFamily: theme.fonts.display, fontSize: 15,
          }}>{o.l}</button>
        ))}
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginBottom: 10 }}>── Toon</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 32 }}>
        <Choice theme={theme} active={data.tone === "speels"} onClick={() => update("tone", "speels")}
          title="Speels & informeel" subtitle="Knipoogjes en popcultuur" />
        <Choice theme={theme} active={data.tone === "zakelijk"} onClick={() => update("tone", "zakelijk")}
          title="Zakelijk & strak" subtitle="Helder en feitelijk" />
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginBottom: 10 }}>── Moeilijkheid</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", border: `1px solid ${theme.rule}` }}>
        {["makkelijk", "gemiddeld", "pittig", "expert"].map((v, i) => (
          <button key={v} onClick={() => update("difficulty", v)} style={{
            background: data.difficulty === v ? theme.fg : "transparent",
            color: data.difficulty === v ? theme.bg : theme.fg,
            border: "none",
            borderRight: i < 3 ? `1px solid ${theme.rule}` : "none",
            padding: "16px 12px", cursor: "pointer",
            fontFamily: theme.fonts.display, fontSize: 18,
            transition: "all .15s",
          }}>{v}</button>
        ))}
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginTop: 28, marginBottom: 10 }}>── Spelen als</Eyebrow>
      <div style={{ display: "flex", gap: 10 }}>
        <Choice theme={theme} active={!data.teams} onClick={() => update("teams", false)} title="Solo" subtitle="Iedereen voor zichzelf" style={{ flex: 1 }} />
        <Choice theme={theme} active={data.teams} onClick={() => update("teams", true)} title="In teams" subtitle="Samen kennis pakken" style={{ flex: 1 }} />
      </div>
    </div>
  );
}

function Step3({ theme, data, update }) {
  const types = [
    { v: "mc", l: "Multiple choice", d: "Vier opties, één juist", g: "A" },
    { v: "tf", l: "Waar / niet waar", d: "Snel en eenvoudig", g: "✓" },
    { v: "open", l: "Open antwoord", d: "Spelers typen zelf", g: "Aa" },
    { v: "img", l: "Beeld-vraag", d: "Foto raden", g: "▢" },
    { v: "buzz", l: "Buzzer", d: "Eerste die drukt", g: "!" },
  ];
  const toggle = (v) => {
    const has = data.types.includes(v);
    update("types", has ? data.types.filter((t) => t !== v) : [...data.types, v]);
  };
  return (
    <div>
      <StepHeader theme={theme} eyebrow="Hoofdstuk III"
        title={<>De vragen <span style={{ }}>zelf</span>.</>}
        intro="Welke typen, hoeveel, en hoe lang mogen spelers nadenken."
      />

      <Eyebrow theme={theme} style={{ display: "block", marginBottom: 10 }}>── Vraagtypes (kies meerdere)</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 32 }}>
        {types.map((t) => {
          const active = data.types.includes(t.v);
          return (
            <Choice key={t.v} theme={theme} active={active} onClick={() => toggle(t.v)}
              glyph={t.g} title={t.l} subtitle={t.d} />
          );
        })}
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
        <Eyebrow theme={theme}>── Aantal vragen</Eyebrow>
        <FigureNum theme={theme} size={36} accent>{data.questionCount}</FigureNum>
      </div>
      <input type="range" min="5" max="40" step="1" value={data.questionCount} onChange={(e) => update("questionCount", +e.target.value)} style={{ width: "100%", accentColor: theme.accent }} />
      <div style={{ display: "flex", justifyContent: "space-between", fontFamily: theme.fonts.mono, fontSize: 10, color: theme.fgDim, marginTop: 4, letterSpacing: "0.1em" }}>
        <span>5</span><span>20</span><span>40</span>
      </div>

      <Eyebrow theme={theme} style={{ display: "block", marginTop: 28, marginBottom: 10 }}>── Tijd per vraag</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", border: `1px solid ${theme.rule}` }}>
        {[10, 20, 30, 60, 0].map((t, i) => (
          <button key={t} onClick={() => update("timer", t)} style={{
            background: data.timer === t ? theme.fg : "transparent",
            color: data.timer === t ? theme.bg : theme.fg,
            border: "none",
            borderRight: i < 4 ? `1px solid ${theme.rule}` : "none",
            padding: "14px 10px",
            fontFamily: theme.fonts.display,
            fontSize: 18,
            cursor: "pointer",
          }}>{t === 0 ? "geen" : `${t} sec`}</button>
        ))}
      </div>
    </div>
  );
}

function Step4({ theme, data, update }) {
  const [generating, setGenerating] = useStateWiz(false);
  const [error, setError] = useStateWiz(null);
  const [elapsed, setElapsed] = useStateWiz(0);
  const [usage, setUsage] = useStateWiz(null);

  useEffectWiz(() => {
    window.kwistApi.get("/api/ai/usage").then(setUsage).catch(() => {});
  }, []);

  const generate = async () => {
    if (generating) return;
    setGenerating(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/ai/generate", {
        topic: data.topic,
        description: data.description,
        audience: data.age ? `${data.audience} (leeftijd ${data.age} jaar)` : data.audience,
        tone: data.tone,
        difficulty: data.difficulty,
        questionCount: data.questionCount,
        types: data.types,
        timer: data.timer,
        teams: data.teams,
        sourceText: data.sourceText || undefined,
      });
      update("generated", res);
      update("genElapsed", Math.round((Date.now() - started) / 100) / 10);
      if (!data.title && res.title) update("title", res.title);
      window.kwistApi.get("/api/ai/usage").then(setUsage).catch(() => {});
    } catch (e) {
      if (e.status === 429 && e.data) {
        setError(e.data.error);
        setUsage({ used: e.data.used, limit: e.data.limit, enabled: true });
      } else {
        setError(e.message || "Generatie mislukt");
      }
    } finally {
      clearInterval(tick);
      setGenerating(false);
    }
  };

  useEffectWiz(() => {
    if (!data.generated) generate();
    // re-generate als topic/difficulty/types/count materieel zijn veranderd na een eerste run
    // bewust níet automatisch: gebruiker drukt zelf "Opnieuw"
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const generated = data.generated;
  const sample = (generated?.questions || []).slice(0, 4);

  return (
    <div>
      <StepHeader theme={theme} eyebrow="Hoofdstuk IV"
        title={<>De <span style={{ }}>proefdruk</span>.</>}
        intro="Bewerk titel, herschud, of genereer opnieuw. Alles is bij te schaven."
      />

      <Field theme={theme} label="── Titel" value={data.title || generated?.title || data.topic} onChange={(v) => update("title", v)} />

      {generating ? (
        <div style={{ marginTop: 24 }}>
          <GeneratingLoader theme={theme} elapsed={elapsed} topic={data.topic} />
        </div>
      ) : (
        <div style={{
          marginTop: 24, padding: "16px 20px",
          background: theme.bg2,
          color: theme.fg,
          border: `1px solid ${error ? theme.accent : theme.rule}`,
          display: "flex", gap: 16, alignItems: "center", justifyContent: "space-between",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            {error ? (
              <>
                <FigureNum theme={theme} size={28} accent>!</FigureNum>
                <div>
                  <div style={{ fontFamily: theme.fonts.display, fontSize: 18 }}>Generatie mislukt.</div>
                  <Eyebrow theme={theme} style={{ color: theme.accent }}>{error}</Eyebrow>
                </div>
              </>
            ) : generated ? (
              <>
                <FigureNum theme={theme} size={28} accent>✓</FigureNum>
                <div>
                  <div style={{ fontFamily: theme.fonts.display, fontSize: 18 }}>{generated.questions?.length || 0} vragen klaar voor de drukpers.</div>
                  <Eyebrow theme={theme}>{(data.genElapsed ?? 0).toFixed(1)} SEC · {(generated.category || "AI GEGENEREERD").toUpperCase()}</Eyebrow>
                </div>
              </>
            ) : (
              <Eyebrow theme={theme}>WACHTEN OP DE REDACTIE…</Eyebrow>
            )}
          </div>
          <Btn theme={theme} size="sm" variant="outline" onClick={generate}>↻ Opnieuw</Btn>
        </div>
      )}

      {usage && usage.enabled && (
        <div style={{
          marginTop: 8, padding: "8px 20px",
          background: usage.used >= usage.limit ? theme.accent + "18" : "transparent",
          border: usage.used >= usage.limit ? `1px solid ${theme.accent}` : `1px solid ${theme.rule}`,
          display: "flex", justifyContent: "space-between", alignItems: "center",
        }}>
          <Eyebrow theme={theme} style={{ color: usage.used >= usage.limit ? theme.accent : theme.muted }}>
            Fair use: {usage.used}/{usage.limit} generaties vandaag
          </Eyebrow>
          {usage.used >= usage.limit && (
            <Eyebrow theme={theme} style={{ color: theme.accent }}>Limiet bereikt</Eyebrow>
          )}
        </div>
      )}

      <div style={{ marginTop: 28 }}>
        <Eyebrow theme={theme} style={{ marginBottom: 10 }}>── Een voorproefje</Eyebrow>
        <div style={{ display: "flex", flexDirection: "column" }}>
          {(sample.length ? sample : Array(4).fill(null)).map((q, i, arr) => (
            <div key={i} style={{
              display: "grid",
              gridTemplateColumns: "40px 1fr 80px",
              gap: 14,
              padding: "14px 0",
              borderBottom: i < arr.length - 1 ? `1px dashed ${theme.rule}` : "none",
              alignItems: "center",
              opacity: q ? 1 : 0.4,
            }}>
              <FigureNum theme={theme} size={22}>{("0" + (i + 1)).slice(-2)}</FigureNum>
              {q ? (
                <>
                  <div>
                    <div style={{ fontFamily: theme.fonts.display, fontSize: 17, lineHeight: 1.25 }}>{q.prompt}</div>
                    <Eyebrow theme={theme} style={{ marginTop: 4, color: theme.accent }}>✓ {answerLabel(q)}</Eyebrow>
                  </div>
                  <Eyebrow theme={theme} style={{ textAlign: "right" }}>{labelForType(q.type)}</Eyebrow>
                </>
              ) : (
                <>
                  <div style={{ height: 14, background: theme.bg2 }} />
                  <div />
                </>
              )}
            </div>
          ))}
          {generated && generated.questions.length > 4 && (
            <div style={{ padding: "12px 0", textAlign: "center" }}>
              <Eyebrow theme={theme}>+ {generated.questions.length - 4} VRAGEN MEER</Eyebrow>
            </div>
          )}
        </div>
      </div>

    </div>
  );
}

// =================== STEP V — questions editor ===================

function Step5({ theme, data, update, onBack }) {
  const questions = (data.generated && data.generated.questions) || [];
  const [expanded, setExpanded] = useStateWiz(0);

  const replaceQuestions = (next) => update("generated", { ...(data.generated || {}), questions: next });

  const move = (i, dir) => {
    const next = [...questions];
    const j = i + dir;
    if (j < 0 || j >= next.length) return;
    [next[i], next[j]] = [next[j], next[i]];
    replaceQuestions(next);
    setExpanded(j);
  };

  const remove = async (i) => {
    const ok = await window.kwistDialog.confirm(
      `Vraag ${i + 1} verwijderen?`,
      { title: "Vraag verwijderen?", danger: true, confirmLabel: "Verwijder" }
    );
    if (!ok) return;
    replaceQuestions(questions.filter((_, k) => k !== i));
    setExpanded(null);
  };

  const updateQ = (i, patch) => {
    const next = questions.map((q, k) => k === i ? { ...q, ...patch } : q);
    replaceQuestions(next);
  };

  const add = () => {
    const next = [...questions, {
      type: "mc",
      prompt: "Nieuwe vraag",
      options: [
        { id: "a", text: "Optie A", correct: true },
        { id: "b", text: "Optie B", correct: false },
        { id: "c", text: "Optie C", correct: false },
        { id: "d", text: "Optie D", correct: false },
      ],
      answer: null,
      timeLimit: data.timer ?? 20,
    }];
    replaceQuestions(next);
    setExpanded(next.length - 1);
  };

  if (!questions.length) {
    return (
      <div>
        <StepHeader theme={theme} eyebrow="Hoofdstuk V"
          title={<>Nog niets om te <span>bewerken</span>.</>}
          intro="Ga eerst terug naar Hoofdstuk IV en laat de AI de vragen genereren."
        />
        <Btn theme={theme} variant="outline" onClick={onBack}>← Terug naar Hoofdstuk IV</Btn>
      </div>
    );
  }

  return (
    <div>
      <StepHeader theme={theme} eyebrow="Hoofdstuk V"
        title={<>Bewerk de <span>vragen</span>.</>}
        intro="Pas teksten aan, sleep met ↑/↓ van volgorde, verwijder wat niet past, of voeg nieuwe toe. Wijzigingen worden meegenomen bij het starten."
      />

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {questions.map((q, i) => (
          <QuestionRow
            key={i}
            theme={theme}
            index={i}
            total={questions.length}
            q={q}
            expanded={expanded === i}
            onToggle={() => setExpanded(expanded === i ? null : i)}
            onMoveUp={() => move(i, -1)}
            onMoveDown={() => move(i, +1)}
            onRemove={() => remove(i)}
            onChange={(patch) => updateQ(i, patch)}
          />
        ))}
      </div>

      <div style={{ marginTop: 18, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Btn theme={theme} variant="outline" onClick={add}>+ Vraag toevoegen</Btn>
        <Eyebrow theme={theme}>{questions.length} VRAGEN · DRUK OP "GENEREER & START" RECHTSONDER</Eyebrow>
      </div>
    </div>
  );
}

function QuestionRow({ theme, index, total, q, expanded, onToggle, onMoveUp, onMoveDown, onRemove, onChange }) {
  return (
    <div style={{ border: `1px solid ${theme.rule}`, background: theme.bg }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: "40px 1fr auto",
        gap: 14,
        padding: "12px 14px",
        alignItems: "center",
        cursor: "pointer",
        background: expanded ? theme.bg2 : "transparent",
      }} onClick={onToggle}>
        <FigureNum theme={theme} size={22}>{("0" + (index + 1)).slice(-2)}</FigureNum>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: theme.fonts.display, fontSize: 18, lineHeight: 1.25, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{q.prompt || <span style={{ color: theme.fgDim }}>(leeg)</span>}</div>
          <Eyebrow theme={theme} style={{ marginTop: 2 }}>{labelForType(q.type)} · {q.timeLimit ?? 20} SEC</Eyebrow>
        </div>
        <div style={{ display: "flex", gap: 4 }} onClick={(e) => e.stopPropagation()}>
          <IconBtn theme={theme} disabled={index === 0} onClick={onMoveUp} title="Omhoog">↑</IconBtn>
          <IconBtn theme={theme} disabled={index === total - 1} onClick={onMoveDown} title="Omlaag">↓</IconBtn>
          <IconBtn theme={theme} onClick={onRemove} danger title="Verwijder">×</IconBtn>
          <IconBtn theme={theme} onClick={onToggle} title={expanded ? "Inklappen" : "Bewerk"}>{expanded ? "−" : "✎"}</IconBtn>
        </div>
      </div>

      {expanded && (
        <div style={{ borderTop: `1px solid ${theme.rule}`, padding: "16px 18px", display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 160px", gap: 16 }}>
            <div>
              <Eyebrow theme={theme} style={{ marginBottom: 4 }}>── Vraag</Eyebrow>
              <textarea
                value={q.prompt}
                onChange={(e) => onChange({ prompt: e.target.value })}
                rows={2}
                style={{
                  width: "100%", background: "transparent", color: theme.fg,
                  border: `1px solid ${theme.rule}`,
                  padding: "12px 14px",
                  fontFamily: theme.fonts.body, fontSize: 17,
                  outline: "none", resize: "vertical", lineHeight: 1.4,
                }}
              />
            </div>
            <div>
              <Eyebrow theme={theme} style={{ marginBottom: 4 }}>── Type</Eyebrow>
              <select
                value={q.type}
                onChange={(e) => {
                  const t = e.target.value;
                  if (t === "mc" && !(q.options && q.options.length)) {
                    onChange({
                      type: t,
                      options: [
                        { id: "a", text: "Optie A", correct: true },
                        { id: "b", text: "Optie B", correct: false },
                        { id: "c", text: "Optie C", correct: false },
                        { id: "d", text: "Optie D", correct: false },
                      ],
                    });
                  } else if (t === "tf") {
                    onChange({ type: t, options: null, answer: q.answer || "waar" });
                  } else if (t === "open") {
                    onChange({ type: t, options: null, answer: q.answer || "" });
                  } else {
                    onChange({ type: t });
                  }
                }}
                style={{
                  width: "100%", padding: "12px 14px",
                  border: `1px solid ${theme.rule}`,
                  background: theme.bg, color: theme.fg,
                  fontFamily: theme.fonts.body, fontSize: 16,
                }}
              >
                <option value="mc">Multiple choice</option>
                <option value="tf">Waar / niet waar</option>
                <option value="open">Open antwoord</option>
              </select>

              <Eyebrow theme={theme} style={{ marginTop: 12, marginBottom: 4 }}>── Tijd (sec)</Eyebrow>
              <input
                type="number" min="0" max="300"
                value={q.timeLimit ?? 20}
                onChange={(e) => onChange({ timeLimit: parseInt(e.target.value, 10) || 0 })}
                style={{
                  width: "100%", padding: "12px 14px",
                  border: `1px solid ${theme.rule}`,
                  background: theme.bg, color: theme.fg,
                  fontFamily: theme.fonts.body, fontSize: 16,
                }}
              />
            </div>
          </div>

          {q.type === "mc" && <McEditor theme={theme} q={q} onChange={onChange} />}
          {q.type === "tf" && (
            <div>
              <Eyebrow theme={theme} style={{ marginBottom: 6 }}>── Juiste antwoord</Eyebrow>
              <div style={{ display: "flex", gap: 8 }}>
                {["waar", "niet waar"].map((v) => (
                  <button key={v} type="button" onClick={() => onChange({ answer: v })} style={{
                    background: q.answer === v ? theme.fg : "transparent",
                    color: q.answer === v ? theme.bg : theme.fg,
                    border: `1px solid ${q.answer === v ? theme.fg : theme.rule}`,
                    padding: "12px 18px", cursor: "pointer",
                    fontFamily: theme.fonts.display, fontSize: 18, textTransform: "uppercase",
                  }}>{v}</button>
                ))}
              </div>
            </div>
          )}
          {q.type === "open" && (
            <div>
              <Eyebrow theme={theme} style={{ marginBottom: 4 }}>── Juiste antwoord (precies)</Eyebrow>
              <input
                value={q.answer || ""}
                onChange={(e) => onChange({ answer: e.target.value })}
                style={{
                  width: "100%", padding: "12px 14px",
                  border: `1px solid ${theme.rule}`,
                  background: theme.bg, color: theme.fg,
                  fontFamily: theme.fonts.body, fontSize: 17,
                }}
              />
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function McEditor({ theme, q, onChange }) {
  const opts = q.options || [];
  const setOpt = (i, patch) => {
    const next = opts.map((o, k) => k === i ? { ...o, ...patch } : o);
    onChange({ options: next });
  };
  const setCorrect = (i) => {
    onChange({ options: opts.map((o, k) => ({ ...o, correct: k === i })) });
  };
  const addOpt = () => {
    if (opts.length >= 6) return;
    const id = String.fromCharCode(97 + opts.length);
    onChange({ options: [...opts, { id, text: "", correct: false }] });
  };
  const removeOpt = (i) => {
    if (opts.length <= 2) return;
    onChange({ options: opts.filter((_, k) => k !== i) });
  };

  return (
    <div>
      <Eyebrow theme={theme} style={{ marginBottom: 6 }}>── Opties · klik op het rondje voor het juiste antwoord</Eyebrow>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {opts.map((o, i) => (
          <div key={i} style={{
            display: "grid",
            gridTemplateColumns: "32px 1fr auto",
            gap: 10,
            alignItems: "center",
            padding: "8px 10px",
            border: `1px solid ${o.correct ? theme.accent : theme.rule}`,
            background: o.correct ? `${theme.accent}10` : "transparent",
          }}>
            <button type="button" onClick={() => setCorrect(i)} title="Markeer als juist" style={{
              width: 22, height: 22, borderRadius: "50%",
              border: `2px solid ${o.correct ? theme.accent : theme.rule}`,
              background: o.correct ? theme.accent : "transparent",
              cursor: "pointer", padding: 0,
            }} />
            <input
              value={o.text}
              onChange={(e) => setOpt(i, { text: e.target.value })}
              placeholder={`Optie ${String.fromCharCode(65 + i)}`}
              style={{
                width: "100%", padding: "10px 12px",
                background: "transparent", color: theme.fg,
                border: "none", outline: "none",
                fontFamily: theme.fonts.body, fontSize: 16,
              }}
            />
            <IconBtn theme={theme} onClick={() => removeOpt(i)} disabled={opts.length <= 2} danger title="Verwijder optie">×</IconBtn>
          </div>
        ))}
      </div>
      {opts.length < 6 && (
        <button type="button" onClick={addOpt} style={{
          marginTop: 8,
          background: "transparent",
          border: `1px dashed ${theme.rule}`,
          padding: "8px 14px",
          cursor: "pointer", color: theme.fg,
          fontFamily: theme.fonts.mono, fontSize: 13, letterSpacing: "0.1em",
        }}>+ EXTRA OPTIE</button>
      )}
    </div>
  );
}

function IconBtn({ theme, children, onClick, disabled, danger, title }) {
  return (
    <button type="button" onClick={onClick} disabled={disabled} title={title} style={{
      width: 30, height: 30,
      background: "transparent",
      border: `1px solid ${danger ? theme.accent : theme.rule}`,
      color: danger ? theme.accent : theme.fg,
      cursor: disabled ? "default" : "pointer",
      opacity: disabled ? 0.3 : 1,
      fontFamily: theme.fonts.display, fontSize: 16, lineHeight: 1,
      display: "grid", placeItems: "center",
    }}>{children}</button>
  );
}

function answerLabel(q) {
  if (q.type === "mc") {
    const correct = (q.options || []).find((o) => o.correct);
    return correct?.text || q.answer || "—";
  }
  return q.answer || "—";
}

function labelForType(t) {
  return ({ mc: "MULTIPLE CHOICE", tf: "WAAR / NIET WAAR", open: "OPEN", img: "BEELD", buzz: "BUZZER" })[t] || (t || "").toUpperCase();
}

function Choice({ theme, active, onClick, title, subtitle, glyph, style }) {
  return (
    <button onClick={onClick} style={{
      background: active ? theme.fg : "transparent",
      color: active ? theme.bg : theme.fg,
      border: `1px solid ${active ? theme.fg : theme.rule}`,
      padding: "14px 18px",
      cursor: "pointer", textAlign: "left",
      fontFamily: theme.fonts.body,
      transition: "all .15s",
      display: "flex", alignItems: "center", gap: 14,
      ...style,
    }}>
      {glyph && (
        <div style={{
          width: 32, height: 32,
          background: active ? theme.bg : theme.card,
          color: active ? theme.fg : theme.accent,
          border: `1px solid ${active ? theme.bg : theme.rule}`,
          display: "grid", placeItems: "center",
          fontFamily: theme.fonts.display, fontSize: 16,
          flexShrink: 0,
        }}>{glyph}</div>
      )}
      <div>
        <div style={{ fontFamily: theme.fonts.display, fontSize: 18 }}>{title}</div>
        {subtitle && <Eyebrow theme={theme} style={{ marginTop: 2, color: active ? "rgba(255,255,255,0.7)" : theme.fgDim }}>{subtitle}</Eyebrow>}
      </div>
    </button>
  );
}

// ============ PREVIEW PANE ============
function PreviewPane({ theme, data, step }) {
  const summary = [
    ["Onderwerp", data.topic || "—"],
    ["Doelgroep", data.audience],
    ["Toon", data.tone],
    ["Moeilijkheid", data.difficulty],
    ["Vragen", data.questionCount],
    ["Timer", data.timer === 0 ? "Geen" : `${data.timer} sec`],
    ["Types", data.types.join(", ").toUpperCase()],
    ["Modus", data.teams ? "Teams" : "Solo"],
  ];

  return (
    <aside style={{ background: theme.bg2, color: theme.fg, padding: "44px 40px", display: "flex", flexDirection: "column", gap: 24, overflowY: "auto" }}>
      <Eyebrow theme={theme} style={{ color: theme.signal }}>── PROEFDRUK · LIVE</Eyebrow>

      {/* mock cover */}
      <div style={{
        background: theme.accent, color: "#fff",
        padding: "28px 24px",
        position: "relative", overflow: "hidden",
        minHeight: 220,
      }}>
        <div style={{
          position: "absolute", top: 14, left: 18, right: 18,
          display: "flex", justifyContent: "space-between",
          fontFamily: theme.fonts.mono, fontSize: 10, letterSpacing: "0.15em", opacity: 0.85,
        }}>
          <span>Nº NIEUW · {data.tone.toUpperCase()}</span>
          <span>VR. {data.questionCount}</span>
        </div>
        <div style={{
          fontFamily: theme.fonts.display,
          fontSize: 30,
          lineHeight: 1.05,
          marginTop: 32,
          letterSpacing: "-0.02em",
        }}>{data.title || data.topic || "Quiz titel"}</div>
        <div style={{
          fontFamily: theme.fonts.display, fontSize: 110, lineHeight: 1, position: "absolute", right: -10, bottom: -20,
          opacity: 0.18,
        }}>✦</div>
        <div style={{
          position: "absolute", bottom: 14, left: 18,
          fontFamily: theme.fonts.mono, fontSize: 10, letterSpacing: "0.12em", opacity: 0.85,
        }}>~{Math.round((data.timer || 25) * data.questionCount / 60)} MIN · {data.teams ? "TEAMS" : "SOLO"}</div>
      </div>

      {/* Live Q1 — uses the actual generated first question if available */}
      {step >= 2 && (() => {
        const firstQ = data.generated?.questions?.[0];
        const fallback = {
          prompt: data.topic ? `Voorbeeldvraag over ${data.topic} (genereren in stap IV)` : "Voorbeeldvraag",
          options: [{ id: "a", text: "Optie A" }, { id: "b", text: "Optie B", correct: true }, { id: "c", text: "Optie C" }, { id: "d", text: "Optie D" }],
          type: "mc",
        };
        const q = firstQ && firstQ.type === "mc" ? firstQ : (firstQ || fallback);
        const opts = (q.options && q.options.length) ? q.options : fallback.options;
        return (
        <div style={{ background: theme.card, padding: 18, border: `1px solid ${theme.rule}` }}>
          <Eyebrow theme={theme} style={{ marginBottom: 8 }}>── VRAAG 01 / {data.generated?.questions?.length || data.questionCount}</Eyebrow>
          <div style={{ fontFamily: theme.fonts.display, fontSize: 19, lineHeight: 1.3, marginBottom: 14 }}>
            {q.prompt}
          </div>
          {q.type === "mc" ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {opts.map((opt, i) => (
              <div key={opt.id || opt.text || i} style={{
                padding: "10px 14px",
                border: `1px solid ${opt.correct ? theme.accent : theme.rule}`,
                background: opt.correct ? `${theme.accent}10` : "transparent",
                fontFamily: theme.fonts.body, fontSize: 13,
                display: "flex", justifyContent: "space-between",
                color: opt.correct ? theme.accent : theme.fg,
              }}>
                <span><span style={{ fontFamily: theme.fonts.mono, marginRight: 10, opacity: 0.6 }}>{String.fromCharCode(65 + i)}.</span>{opt.text || opt.l}</span>
                {opt.correct && <span style={{ fontFamily: theme.fonts.display, }}>✓ juist</span>}
              </div>
            ))}
          </div>
          ) : (
            <div style={{
              padding: "10px 14px",
              border: `1px solid ${theme.accent}`,
              background: `${theme.accent}10`,
              color: theme.accent,
              fontFamily: theme.fonts.body, fontSize: 13,
            }}>✓ {q.answer || "—"}</div>
          )}
        </div>
        );
      })()}

      <div style={{ background: theme.card, border: `1px solid ${theme.rule}` }}>
        <div style={{ padding: "10px 16px", borderBottom: `1px solid ${theme.rule}` }}>
          <Eyebrow theme={theme}>── COLOFON</Eyebrow>
        </div>
        {summary.map(([k, v], i) => (
          <div key={k} style={{
            display: "flex", justifyContent: "space-between",
            padding: "10px 16px",
            borderBottom: i < summary.length - 1 ? `1px dashed ${theme.rule}` : "none",
            fontFamily: theme.fonts.body, fontSize: 13,
          }}>
            <span style={{ color: theme.fgDim, fontFamily: theme.fonts.mono, fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase" }}>{k}</span>
            <span style={{ fontFamily: theme.fonts.display, fontSize: 15, textAlign: "right", maxWidth: "60%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{String(v)}</span>
          </div>
        ))}
      </div>
    </aside>
  );
}

window.WizardScreen = WizardScreen;
window.QuestionRow = QuestionRow;
