// Quizrs — Player (plays a real quiz/poll). Quiz mode scores against `correct`;
// poll mode (correct === null) records a choice with no right/wrong.

function PlayerPicker({ go }) {
  const { quizzes } = useStore();
  const playable = quizzes;
  return (
    <div className="screen-pad fade">
      <h2 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.5px", margin: "0 0 4px" }}>Play a quiz</h2>
      <div className="muted" style={{ fontSize: 13.5, marginBottom: 18 }}>Pick one to preview the student experience.</div>
      {playable.length === 0 ? (
        <EmptyState icon="play" title="No quizzes to play yet" hint="Create one first."
          action={<Btn kind="primary" sm icon="plus" onClick={() => go("creator")}>New quiz</Btn>} />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px,1fr))", gap: 14 }}>
          {playable.map((q) => (
            <button key={q.id} className="card" onClick={() => go("player", { id: q.id })}
              style={{ textAlign: "left", cursor: "pointer", padding: 0, overflow: "hidden", font: "inherit", color: "inherit" }}>
              <Cover tint={q.tint} glyph={q.glyph} h={88} r={0} />
              <div className="card-pad">
                <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                  <StatusBadge status={q.status} />
                  <span className="muted mono" style={{ fontSize: 11 }}>{q.questionCount} {q.isPoll ? "options" : "Qs"}</span>
                </div>
                <div style={{ fontWeight: 650, fontSize: 14.5, lineHeight: 1.3 }}>{q.title}</div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function PlayerRun({ quiz, go }) {
  const isPoll = quiz.isPoll;
  const qs = quiz.questions || [];
  const [idx, setIdx] = React.useState(0);
  const [picked, setPicked] = React.useState(null);
  const [revealed, setRevealed] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [answered, setAnswered] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [secs, setSecs] = React.useState(0);

  React.useEffect(() => {
    if (done) return;
    const t = setInterval(() => setSecs((s) => s + 1), 1000);
    return () => clearInterval(t);
  }, [done]);

  if (!qs.length) {
    return <div className="screen-pad"><EmptyState icon="play" title="This quiz has no questions yet." action={<Btn kind="ghost" icon="chevL" onClick={() => go("library")}>Back</Btn>} /></div>;
  }

  const q = qs[idx];
  const isLast = idx === qs.length - 1;

  function submit() {
    if (picked == null) return;
    setRevealed(true);
    setAnswered((a) => a + 1);
    if (!isPoll && picked === q.correct) setScore((s) => s + 1);
  }
  function next() {
    if (isLast) { setDone(true); return; }
    setIdx((i) => i + 1); setPicked(null); setRevealed(false);
  }
  function restart() { setIdx(0); setPicked(null); setRevealed(false); setScore(0); setAnswered(0); setDone(false); setSecs(0); }

  const mm = String(Math.floor(secs / 60));
  const ss = String(secs % 60).padStart(2, "0");

  if (done) return <PlayerResult quiz={quiz} score={score} answered={answered} total={qs.length} time={`${mm}:${ss}`} restart={restart} go={go} />;

  return (
    <div className="fade" style={{ height: "100%", display: "flex", flexDirection: "column",
      background: "radial-gradient(120% 80% at 50% -10%, var(--accent-tint) 0%, transparent 55%), var(--bg)" }}>
      <div className="row" style={{ padding: "16px 24px", gap: 12 }}>
        <Btn kind="quiet" sm icon="x" onClick={() => go("library")}>Exit</Btn>
        <div style={{ flex: 1, maxWidth: 520, margin: "0 auto" }}>
          <div className="row" style={{ gap: 10 }}>
            <span className="mono muted" style={{ fontSize: 12, fontWeight: 600 }}>{idx + 1}/{qs.length}</span>
            <div style={{ flex: 1 }}><Progress pct={((idx + (revealed ? 1 : 0)) / qs.length) * 100} /></div>
          </div>
        </div>
        <Badge tone="outline" className="mono"><Icon name="clock" size={13} />{mm}:{ss}</Badge>
      </div>

      <div style={{ flex: 1, display: "grid", placeItems: "center", padding: "8px 24px 32px", minHeight: 0, overflowY: "auto" }}>
        <div className="card" style={{ width: "100%", maxWidth: 600, padding: 32, boxShadow: "var(--shadow-lg)" }}>
          <div className="row" style={{ gap: 8, marginBottom: 14 }}>
            <Cover tint={quiz.tint} glyph={quiz.glyph} h={26} r={7} />
            <span className="muted" style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{quiz.title}</span>
            <span style={{ flex: 1 }} />
            <Badge tone="">{isPoll ? "Poll" : "Multiple choice"}</Badge>
          </div>

          <h2 style={{ fontSize: 25, fontWeight: 700, letterSpacing: "-.5px", lineHeight: 1.25, margin: "4px 0 22px" }}>{q.q}</h2>

          <div className="col" style={{ gap: 11 }}>
            {q.opts.map((opt, i) => {
              const isPicked = picked === i;
              const isCorrect = !isPoll && i === q.correct;
              let bd = "var(--border)", bg = "var(--surface)", ring = "none", letterBg = "var(--surface-2)", letterCol = "var(--ink-3)", icon = null;
              if (!revealed && isPicked) { bd = "var(--accent)"; bg = "var(--accent-tint)"; ring = "0 0 0 3px var(--accent-tint)"; letterBg = "var(--accent)"; letterCol = "#fff"; }
              if (revealed && isPoll && isPicked) { bd = "var(--accent)"; bg = "var(--accent-tint)"; letterBg = "var(--accent)"; letterCol = "#fff"; icon = "check"; }
              if (revealed && !isPoll && isCorrect) { bd = "var(--green)"; bg = "var(--green-tint)"; letterBg = "var(--green)"; letterCol = "#fff"; icon = "check"; }
              if (revealed && !isPoll && isPicked && !isCorrect) { bd = "var(--red)"; bg = "var(--red-tint)"; letterBg = "var(--red)"; letterCol = "#fff"; icon = "x"; }
              return (
                <button key={i} disabled={revealed} onClick={() => setPicked(i)}
                  style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 17px", textAlign: "left",
                    border: "1.5px solid " + bd, background: bg, borderRadius: "var(--r)", boxShadow: ring,
                    cursor: revealed ? "default" : "pointer", font: "inherit", color: "inherit" }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, flex: "0 0 auto", display: "grid", placeItems: "center",
                    background: letterBg, color: letterCol, fontWeight: 700, fontSize: 14, fontFamily: "var(--mono)" }}>
                    {icon ? <Icon name={icon} size={16} sw={3} /> : String.fromCharCode(65 + i)}
                  </span>
                  <span style={{ flex: 1, fontSize: 16, fontWeight: 550 }}>{opt}</span>
                </button>
              );
            })}
          </div>

          {revealed && (
            <div className="fade" style={{ marginTop: 16, padding: "13px 15px", borderRadius: "var(--r)",
              background: isPoll || picked === q.correct ? "var(--green-tint)" : "var(--amber-tint)", display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name={isPoll || picked === q.correct ? "check" : "sparkle"} size={17}
                style={{ color: isPoll || picked === q.correct ? "var(--green)" : "var(--amber)", marginTop: 1 }} />
              <div style={{ fontSize: 13.5, lineHeight: 1.45 }}>
                {isPoll
                  ? <><b>Response recorded.</b> Thanks for sharing your choice.</>
                  : picked === q.correct
                    ? <><b>Correct!</b> Nice work.</>
                    : <><b>Not quite.</b> The correct answer is <b>{q.opts[q.correct]}</b>.</>}
              </div>
            </div>
          )}

          <div className="row" style={{ marginTop: 22, gap: 10 }}>
            <span className="muted" style={{ fontSize: 12.5 }}>
              {!revealed ? "Select an answer, then submit" : isPoll ? "Choice recorded" : `Score so far · ${score}/${idx + 1}`}
            </span>
            <span style={{ flex: 1 }} />
            {!revealed
              ? <Btn kind="primary" iconR="arrowR" disabled={picked == null} onClick={submit}>Submit</Btn>
              : <Btn kind="primary" iconR="arrowR" onClick={next}>{isLast ? "Finish" : "Next"}</Btn>}
          </div>
        </div>
      </div>
    </div>
  );
}

function PlayerResult({ quiz, score, answered, total, time, restart, go }) {
  const isPoll = quiz.isPoll;
  const pct = Math.round((score / total) * 100);
  const passed = pct >= 60;
  return (
    <div className="fade" style={{ height: "100%", display: "grid", placeItems: "center", padding: 24,
      background: "radial-gradient(120% 80% at 50% -10%, var(--accent-tint) 0%, transparent 55%), var(--bg)" }}>
      <div className="card" style={{ width: "100%", maxWidth: 460, padding: 36, textAlign: "center", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ width: 64, height: 64, borderRadius: 18, margin: "0 auto 16px", display: "grid", placeItems: "center",
          background: isPoll || passed ? "var(--green-tint)" : "var(--amber-tint)", color: isPoll || passed ? "var(--green)" : "var(--amber)" }}>
          <Icon name={isPoll ? "check" : passed ? "trophy" : "flag"} size={30} />
        </div>
        <div className="muted" style={{ fontSize: 13.5, fontWeight: 600 }}>{isPoll ? "Poll complete" : "Quiz complete"}</div>
        <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.5px", margin: "3px 0 4px" }}>
          {isPoll ? "Thanks!" : passed ? "Well done!" : "Good effort!"}
        </h2>
        {!isPoll && (
          <div style={{ fontSize: 60, fontWeight: 800, letterSpacing: "-2px", lineHeight: 1.05, margin: "10px 0", color: passed ? "var(--green)" : "var(--amber)" }}>{pct}%</div>
        )}
        <div className="muted" style={{ fontSize: 14 }}>
          {isPoll ? <>You answered <b style={{ color: "var(--ink)" }}>{answered} of {total}</b></> : <>You got <b style={{ color: "var(--ink)" }}>{score} of {total}</b> correct</>}
        </div>

        <div className="row" style={{ gap: 10, margin: "22px 0", justifyContent: "center" }}>
          {!isPoll && <ResultStat icon="check" label="Correct" value={score} />}
          {!isPoll && <ResultStat icon="x" label="Missed" value={total - score} />}
          {isPoll && <ResultStat icon="check" label="Answered" value={answered} />}
          <ResultStat icon="clock" label="Time" value={time} />
        </div>

        <div className="row" style={{ gap: 10 }}>
          <Btn kind="ghost" icon="arrowR" style={{ flex: 1 }} onClick={restart}>Retry</Btn>
          <Btn kind="primary" icon="stats" style={{ flex: 1 }} onClick={() => go("stats", { id: quiz.id })}>See results</Btn>
        </div>
      </div>
    </div>
  );
}

function ResultStat({ icon, label, value }) {
  return (
    <div style={{ flex: 1, padding: "12px 8px", background: "var(--surface-2)", borderRadius: "var(--r-sm)" }}>
      <Icon name={icon} size={16} className="muted" />
      <div style={{ fontSize: 19, fontWeight: 700, marginTop: 4 }} className="tnum">{value}</div>
      <div className="muted" style={{ fontSize: 11.5, fontWeight: 600 }}>{label}</div>
    </div>
  );
}

function Player({ go, params }) {
  const { getQuiz, getPublicQuiz } = 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("");
    // Prefer the owner endpoint (works for drafts); fall back to public.
    getQuiz(id)
      .then((q) => { if (active) setQuiz(q); })
      .catch(() => getPublicQuiz(id).then((q) => { if (active) setQuiz(q); }))
      .catch((e) => { if (active) setErr(e.message || "Could not load quiz."); })
      .finally(() => { if (active) setLoading(false); });
    return () => { active = false; };
  }, [id, getQuiz, getPublicQuiz]);

  if (!id) return <PlayerPicker 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 <PlayerRun quiz={quiz} go={go} key={quiz.id} />;
}

window.Player = Player;
