// Quizrs — Results. Derived from GET /v1/quizzes/:id/analytics (response counts,
// completion, per-question option distribution) joined with the quiz questions.

function Legend({ color, label }) {
  return <span className="row" style={{ gap: 6 }}><span style={{ width: 9, height: 9, borderRadius: 3, background: color }} /><span className="muted" style={{ fontWeight: 500 }}>{label}</span></span>;
}

// Per-question stat: for quizzes, % who picked the correct option; for polls, the
// leading option's share. counts[i] is an array of per-option response counts.
function questionStats(quiz, optionCounts) {
  return (quiz.questions || []).map((qq, i) => {
    const counts = Array.isArray(optionCounts?.[i]) ? optionCounts[i] : [];
    const total = counts.reduce((a, n) => a + (Number(n) || 0), 0);
    if (!total) return { n: i + 1, q: qq.q, pct: null, total: 0, top: null };
    if (quiz.isPoll) {
      const max = Math.max(...counts);
      const topIdx = counts.indexOf(max);
      return { n: i + 1, q: qq.q, pct: Math.round((max / total) * 100), total, top: qq.opts[topIdx] };
    }
    const correctIdx = qq.correct ?? 0;
    return { n: i + 1, q: qq.q, pct: Math.round(((counts[correctIdx] || 0) / total) * 100), total, top: null };
  });
}

function Stats({ go, params }) {
  const { getQuiz, getAnalytics, shareUrlFor } = useStore();
  const id = params?.id;
  const [tab, setTab] = React.useState("overview");
  const [quiz, setQuiz] = React.useState(null);
  const [analytics, setAnalytics] = 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("");
    Promise.all([getQuiz(id), getAnalytics(id).catch(() => null)])
      .then(([q, a]) => { if (active) { setQuiz(q); setAnalytics(a); } })
      .catch((e) => { if (active) setErr(e.message || "Failed to load results."); })
      .finally(() => { if (active) setLoading(false); });
    return () => { active = false; };
  }, [id, getQuiz, getAnalytics]);

  if (!id) return <div className="screen-pad"><EmptyState icon="stats" title="Pick a quiz to see its results" hint="Open one from your library." action={<Btn kind="ghost" icon="library" onClick={() => go("library")}>Library</Btn>} /></div>;
  if (loading) return <Loading label="Loading results…" />;
  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 results…" />;

  const submissions = Number(analytics?.submissionCount || quiz.submissionCount || 0);
  const completions = Number(analytics?.completionCount || quiz.completionCount || 0);
  const completionRate = analytics?.completionRate != null
    ? Math.round(Number(analytics.completionRate) * (Number(analytics.completionRate) <= 1 ? 100 : 1))
    : submissions ? Math.round((completions / submissions) * 100) : 0;
  const qstats = questionStats(quiz, analytics?.questionOptionCounts);
  const answered = qstats.filter((s) => s.pct != null);
  const avgCorrect = !quiz.isPoll && answered.length ? Math.round(answered.reduce((a, s) => a + s.pct, 0) / answered.length) : null;
  const hasData = submissions > 0 && answered.length > 0;

  return (
    <div className="screen-pad fade">
      <button onClick={() => go("library")} className="row muted"
        style={{ gap: 6, border: 0, background: "transparent", cursor: "pointer", font: "inherit", fontSize: 13, fontWeight: 600, padding: 0, marginBottom: 14 }}>
        <Icon name="chevL" size={15} /> Library
      </button>

      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 20 }}>
        <div className="row" style={{ gap: 14 }}>
          <div style={{ width: 52, flex: "0 0 auto" }}><Cover tint={quiz.tint} glyph={quiz.glyph} h={52} /></div>
          <div>
            <div className="row" style={{ gap: 9, marginBottom: 4 }}>
              <h2 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.5px", margin: 0 }}>{quiz.title}</h2>
              <StatusBadge status={quiz.status} />
            </div>
            <div className="muted" style={{ fontSize: 13.5 }}>{quiz.subject} · {quiz.questionCount} {quiz.isPoll ? "options" : "questions"} · updated {quiz.updated}</div>
          </div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <Btn kind="ghost" icon="eye" onClick={() => go("player", { id: quiz.id })}>Preview</Btn>
          <Btn kind="primary" icon="edit" onClick={() => go("creator", { id: quiz.id })}>Edit</Btn>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 20 }}>
        <Stat k="Responses" icon="play" v={submissions.toLocaleString()} delta="all time" up />
        <Stat k="Completed" icon="check" v={completions.toLocaleString()} delta={`${completionRate}% rate`} up />
        <Stat k={quiz.isPoll ? "Top consensus" : "Avg. correct"} icon="stats" v={quiz.isPoll ? (qstats.find((s) => s.pct != null)?.pct ?? 0) + "%" : (avgCorrect != null ? avgCorrect + "%" : "—")} delta="" up />
        <Stat k="Questions" icon="list" v={String(quiz.questionCount)} delta={quiz.isPoll ? "poll" : quiz.difficulty || ""} up />
      </div>

      {quiz.responseCollectionMode === "off" && (
        <ErrorNote>Response collection is off. Turn it on in the Creator to gather results.</ErrorNote>
      )}

      {!hasData ? (
        <EmptyState icon="stats" title="No responses yet"
          hint={quiz.status === "live" ? "Share the quiz to start collecting results." : "Publish and share the quiz to collect results."}
          action={<Btn kind="primary" sm icon="copy" onClick={() => navigator.clipboard?.writeText(shareUrlFor(quiz))}>Copy share link</Btn>} />
      ) : (
        <>
          <div className="row" style={{ gap: 4, marginBottom: 18, borderBottom: "1px solid var(--border)" }}>
            {[["overview", "Overview"], ["questions", quiz.isPoll ? "Per-question results" : "Question breakdown"]].map(([t, label]) => (
              <button key={t} onClick={() => setTab(t)}
                style={{ font: "inherit", fontSize: 14, fontWeight: 600, padding: "10px 14px", cursor: "pointer", background: "transparent",
                  border: 0, borderBottom: "2px solid " + (tab === t ? "var(--accent)" : "transparent"),
                  color: tab === t ? "var(--ink)" : "var(--ink-3)", marginBottom: -1 }}>{label}</button>
            ))}
          </div>

          {tab === "overview" && (
            <section className="card card-pad">
              <div className="row" style={{ marginBottom: 18 }}>
                <h3 className="h-sec" style={{ margin: 0 }}>{quiz.isPoll ? "Leading choice per question" : "Question difficulty"}</h3>
                <span style={{ flex: 1 }} />
                <span className="muted" style={{ fontSize: 12 }}>{quiz.isPoll ? "% picking the top option" : "% answered correctly"}</span>
              </div>
              <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height: 180, padding: "0 2px" }}>
                {qstats.map((s) => {
                  const pct = s.pct ?? 0;
                  const hard = pct < 60, mid = pct < 75;
                  const col = quiz.isPoll ? "var(--accent)" : hard ? "var(--red)" : mid ? "var(--amber)" : "var(--green)";
                  return (
                    <div key={s.n} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6, height: "100%", justifyContent: "flex-end" }}>
                      <span className="tnum" style={{ fontSize: 10.5, fontWeight: 700, color: "var(--ink-3)" }}>{s.pct == null ? "–" : s.pct}</span>
                      <div title={`Q${s.n}: ${s.pct ?? 0}%`} style={{ width: "100%", maxWidth: 26, height: `${pct}%`, background: col, borderRadius: "5px 5px 2px 2px", opacity: .9 }} />
                      <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{s.n}</span>
                    </div>
                  );
                })}
              </div>
              {!quiz.isPoll && (
                <div className="row" style={{ gap: 16, marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--hairline)", fontSize: 12 }}>
                  <Legend color="var(--green)" label="Mastered (≥75%)" />
                  <Legend color="var(--amber)" label="Review (60–74%)" />
                  <Legend color="var(--red)" label="Struggled (<60%)" />
                </div>
              )}
            </section>
          )}

          {tab === "questions" && (
            <div className="card" style={{ overflow: "hidden" }}>
              {qstats.map((s, i) => {
                const pct = s.pct ?? 0;
                const hard = pct < 60, mid = pct < 75;
                const col = quiz.isPoll ? "var(--accent)" : hard ? "var(--red)" : mid ? "var(--amber)" : "var(--green)";
                const tone = quiz.isPoll ? "accent" : hard ? "red" : mid ? "amber" : "green";
                return (
                  <div key={s.n} style={{ display: "grid", gridTemplateColumns: "34px 1fr 130px 110px", gap: 14, alignItems: "center",
                    padding: "13px 18px", borderTop: i ? "1px solid var(--hairline)" : 0 }}>
                    <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-4)" }}>{String(s.n).padStart(2, "0")}</span>
                    <span style={{ fontSize: 14, fontWeight: 550, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.q}</span>
                    <div className="row"><div style={{ flex: 1 }}><Progress pct={pct} color={col} /></div></div>
                    <span className="row" style={{ justifyContent: "flex-end" }}>
                      <Badge tone={tone}>{s.pct == null ? "no data" : quiz.isPoll ? `${s.pct}% top` : `${s.pct}% correct`}</Badge>
                    </span>
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}
    </div>
  );
}

window.Stats = Stats;
