// Quizrs — Creator. Mirrors the classic flow: generate → review questions →
// publish / set response collection. (The backend has no per-question edit
// endpoint, so the question editor is review-only for now.)

const DIFFICULTIES = ["easy", "medium", "hard"];
const RESPONSE_MODES = [
  ["off", "Off"],
  ["creator_only", "Creator only"],
  ["public", "Public"],
];

function GenerateForm({ go }) {
  const { generate, usage } = useStore();
  const [mode, setMode] = React.useState("topic");
  const [contentType, setContentType] = React.useState("quiz");
  const [inputText, setInputText] = React.useState("");
  const [count, setCount] = React.useState(8);
  const [difficulty, setDifficulty] = React.useState("medium");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");

  const atLimit = usage?.quotaLimit != null && usage.quizzesUsed >= usage.quotaLimit;

  async function submit() {
    if (!inputText.trim() || busy) return;
    setBusy(true); setErr("");
    try {
      const quiz = await generate({ inputText, mode, contentType, questionCount: count, difficulty });
      if (quiz?.id) go("creator", { id: quiz.id });
    } catch (e) {
      setErr(e.message || "Generation failed.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="fade" style={{ height: "100%", overflowY: "auto", background: "radial-gradient(120% 70% at 50% -10%, var(--accent-tint) 0%, transparent 50%), var(--bg)" }}>
      <div style={{ maxWidth: 620, margin: "0 auto", padding: "40px 28px 60px" }}>
        <div className="row" style={{ gap: 9, marginBottom: 6 }}>
          <Icon name="sparkle" size={20} style={{ color: "var(--accent)" }} />
          <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-.5px", margin: 0 }}>Create with AI</h2>
        </div>
        <div className="muted" style={{ fontSize: 14, marginBottom: 24 }}>Generate a quiz or poll from a topic or your own content.</div>

        <ErrorNote>{err}</ErrorNote>
        {atLimit && <ErrorNote>You've reached your plan limit ({usage.quizzesUsed}/{usage.quotaLimit}). Upgrade to generate more.</ErrorNote>}

        <div className="card card-pad" style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="row" style={{ gap: 10 }}>
            <SegBar value={contentType} onChange={setContentType} options={[["quiz", "Quiz"], ["poll", "Poll"]]} />
            <span style={{ flex: 1 }} />
            <SegBar value={mode} onChange={setMode} options={[["topic", "Topic"], ["content", "Paste content"]]} />
          </div>

          <div>
            <label className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase" }}>
              {mode === "topic" ? "Topic" : "Source content"}
            </label>
            <textarea value={inputText} onChange={(e) => setInputText(e.target.value)} autoFocus
              placeholder={mode === "topic" ? "e.g. Photosynthesis & plant energy for grade 8 biology" : "Paste an article, notes, or passage to base questions on…"}
              style={{ width: "100%", marginTop: 8, minHeight: mode === "topic" ? 70 : 150, resize: "vertical", padding: "13px 15px",
                border: "1px solid var(--border)", borderRadius: "var(--r)", background: "var(--surface)", color: "var(--ink)", fontSize: 15, lineHeight: 1.5, font: "inherit" }} />
          </div>

          <div className="row" style={{ gap: 18, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                <label className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase" }}>{contentType === "poll" ? "Questions" : "Questions"}</label>
                <span className="tnum" style={{ fontWeight: 700, fontSize: 14 }}>{count}</span>
              </div>
              <input type="range" min={3} max={15} step={1} value={count} onChange={(e) => setCount(Number(e.target.value))} style={{ width: "100%" }} />
            </div>
            {contentType !== "poll" && (
              <div style={{ flex: "0 0 auto" }}>
                <label className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", display: "block", marginBottom: 6 }}>Difficulty</label>
                <SegBar value={difficulty} onChange={setDifficulty} options={DIFFICULTIES.map((d) => [d, d[0].toUpperCase() + d.slice(1)])} />
              </div>
            )}
          </div>

          <Btn kind="primary" icon={busy ? null : "sparkle"} disabled={!inputText.trim() || busy || atLimit} onClick={submit} style={{ alignSelf: "flex-start" }}>
            {busy ? <><Spinner size={15} /> Generating…</> : `Generate ${contentType}`}
          </Btn>
        </div>
      </div>
    </div>
  );
}

function QuestionReview({ quiz, go }) {
  const { publish, setResponseMode } = useStore();
  const [active, setActive] = React.useState(0);
  const [q, setQuiz] = React.useState(quiz);
  const [busy, setBusy] = React.useState("");
  const [err, setErr] = React.useState("");
  const [share, setShare] = React.useState(null);

  const questions = q.questions || [];
  const cur = questions[active] || { q: "", opts: [], correct: null };
  const isLive = q.status === "live";

  async function togglePublish() {
    setBusy("publish"); setErr("");
    try { setQuiz(await publish(q.id, !isLive)); } catch (e) { setErr(e.message); } finally { setBusy(""); }
  }
  async function changeMode(mode) {
    setBusy("mode"); setErr("");
    try { setQuiz(await setResponseMode(q.id, mode)); } catch (e) { setErr(e.message); } finally { setBusy(""); }
  }

  return (
    <div className="fade" style={{ display: "grid", gridTemplateColumns: "232px 1fr 300px", height: "100%", minHeight: 0 }}>
      {share && <ShareDialog quiz={q} onClose={() => setShare(null)} />}
      {/* question rail */}
      <aside style={{ borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column", background: "var(--surface)", minHeight: 0 }}>
        <div style={{ padding: "16px 16px 12px" }}>
          <div className="row" style={{ gap: 8 }}>
            <Cover tint={q.tint} glyph={q.glyph} h={30} r={8} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{q.title}</div>
              <div className="muted" style={{ fontSize: 11.5 }}>{q.subject} · {isLive ? "Live" : "Draft"}</div>
            </div>
          </div>
        </div>
        <div className="divider" />
        <div style={{ flex: 1, overflowY: "auto", padding: 10 }}>
          <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".5px", textTransform: "uppercase", padding: "4px 6px 8px" }}>{q.isPoll ? "Poll questions" : "Questions"}</div>
          <div className="col" style={{ gap: 4 }}>
            {questions.map((qq, i) => {
              const on = i === active;
              return (
                <button key={i} onClick={() => setActive(i)}
                  style={{ display: "flex", gap: 10, alignItems: "flex-start", textAlign: "left", padding: "9px 10px",
                    border: "1px solid " + (on ? "var(--accent)" : "transparent"), borderRadius: "var(--r-sm)",
                    background: on ? "var(--accent-tint)" : "transparent", cursor: "pointer", font: "inherit", color: "inherit", width: "100%" }}>
                  <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: on ? "var(--accent-ink)" : "var(--ink-4)", marginTop: 1, width: 16 }}>{String(i + 1).padStart(2, "0")}</span>
                  <span style={{ fontSize: 12.5, fontWeight: on ? 600 : 500, lineHeight: 1.3, color: on ? "var(--ink)" : "var(--ink-2)",
                    display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{qq.q}</span>
                </button>
              );
            })}
          </div>
        </div>
      </aside>

      {/* editor (review) */}
      <main style={{ overflowY: "auto", minHeight: 0, background: "var(--bg)" }}>
        <div style={{ maxWidth: 660, margin: "0 auto", padding: "28px 32px 60px" }}>
          <div className="row" style={{ justifyContent: "space-between", marginBottom: 20 }}>
            <div className="row" style={{ gap: 10 }}>
              <Badge tone="accent">{q.isPoll ? "Poll question" : "Question"} {active + 1}</Badge>
              <span className="muted" style={{ fontSize: 13 }}>of {questions.length}</span>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <Btn kind="ghost" sm icon="chevL" disabled={active === 0} onClick={() => setActive(Math.max(0, active - 1))} />
              <Btn kind="ghost" sm icon="chevR" disabled={active === questions.length - 1} onClick={() => setActive(Math.min(questions.length - 1, active + 1))} />
            </div>
          </div>

          <label className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase" }}>Question</label>
          <div style={{ marginTop: 8, marginBottom: 18, padding: "16px 18px", background: "var(--surface)", border: "1px solid var(--border)",
            borderRadius: "var(--r)", fontSize: 20, fontWeight: 650, letterSpacing: "-.3px", lineHeight: 1.3 }}>{cur.q}</div>

          <div className="row" style={{ justifyContent: "space-between", marginBottom: 12 }}>
            <label className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase" }}>{q.isPoll ? "Options" : "Answer options"}</label>
            {!q.isPoll && <span className="muted" style={{ fontSize: 12 }}>Correct answer highlighted</span>}
          </div>

          <div className="col" style={{ gap: 10 }}>
            {cur.opts.map((opt, i) => {
              const isC = !q.isPoll && i === cur.correct;
              return (
                <div key={i} className="row" style={{ gap: 12, padding: "13px 15px", background: "var(--surface)",
                  border: "1px solid " + (isC ? "var(--green)" : "var(--border)"), borderRadius: "var(--r)",
                  boxShadow: isC ? "0 0 0 3px var(--green-tint)" : "none" }}>
                  <span style={{ width: 24, height: 24, borderRadius: 99, flex: "0 0 auto", display: "grid", placeItems: "center",
                    border: "2px solid " + (isC ? "var(--green)" : "var(--border)"), background: isC ? "var(--green)" : "transparent", color: "#fff" }}>
                    {isC && <Icon name="check" size={13} sw={3} />}
                  </span>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-4)" }}>{String.fromCharCode(65 + i)}</span>
                  <span style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>{opt}</span>
                </div>
              );
            })}
          </div>
        </div>
      </main>

      {/* settings rail */}
      <aside style={{ borderLeft: "1px solid var(--border)", background: "var(--surface)", overflowY: "auto", minHeight: 0, padding: 18 }}>
        <h3 className="h-sec" style={{ margin: "0 0 14px" }}>Quiz settings</h3>
        <ErrorNote>{err}</ErrorNote>
        <div className="col" style={{ gap: 16 }}>
          <div>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 8 }}>
              <span className="muted" style={{ fontSize: 13, fontWeight: 600 }}>Status</span>
              <StatusBadge status={q.status} />
            </div>
            <Btn kind={isLive ? "ghost" : "primary"} icon={busy === "publish" ? null : (isLive ? "eye" : "check")} disabled={busy === "publish"} style={{ width: "100%" }} onClick={togglePublish}>
              {busy === "publish" ? <><Spinner size={14} /> Saving…</> : isLive ? "Unpublish" : "Publish"}
            </Btn>
          </div>

          <div>
            <div className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", marginBottom: 8 }}>Collect responses</div>
            <SegBar value={q.responseCollectionMode || "off"} onChange={changeMode} options={RESPONSE_MODES} />
            <div className="muted" style={{ fontSize: 12, marginTop: 7, lineHeight: 1.45 }}>
              {q.responseCollectionMode === "public" ? "Anyone with the link contributes to results." :
               q.responseCollectionMode === "creator_only" ? "Only you can collect responses." :
               "Responses are not collected."}
            </div>
          </div>
        </div>

        <div className="divider" style={{ margin: "18px 0" }} />
        <div className="col" style={{ gap: 8 }}>
          <Btn kind="primary" icon="eye" style={{ width: "100%" }} onClick={() => go("player", { id: q.id })}>Preview / play</Btn>
          <Btn kind="ghost" icon="copy" style={{ width: "100%" }} onClick={() => setShare(q)}>Share &amp; embed</Btn>
          <Btn kind="ghost" icon="stats" style={{ width: "100%" }} onClick={() => go("stats", { id: q.id })}>View results</Btn>
        </div>
      </aside>
    </div>
  );
}

function Creator({ go, params }) {
  const { getQuiz } = useStore();
  const id = params?.id;
  const [quiz, setQuiz] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    let active = true;
    if (!id) { setQuiz(null); return; }
    setLoading(true); setErr("");
    getQuiz(id).then((q) => { if (active) setQuiz(q); })
      .catch((e) => { if (active) setErr(e.message || "Failed to load quiz."); })
      .finally(() => { if (active) setLoading(false); });
    return () => { active = false; };
  }, [id, getQuiz]);

  if (!id) return <GenerateForm go={go} />;
  if (loading) return <Loading label="Loading quiz…" />;
  if (err) return <div className="screen-pad"><ErrorNote>{err}</ErrorNote><Btn kind="ghost" icon="chevL" onClick={() => go("library")}>Back to library</Btn></div>;
  if (!quiz) return <Loading label="Loading quiz…" />;
  return <QuestionReview quiz={quiz} go={go} key={quiz.id} />;
}

window.Creator = Creator;
window.GenerateForm = GenerateForm;
