/* ==================================================================
   Class Reports — class + test picker → class-level summary
   ================================================================== */

const { Icon: RIcon, StatusPill: RStatusPill } = window.AppUI;

const ClassReports = ({ setScreen }) => {
  const [selection, setSelection] = React.useState(null); // {className, test}

  if (!selection) {
    return <ReportsPicker onPick={(sel) => setSelection(sel)}/>;
  }
  return <ClassReportView selection={selection} onChange={() => setSelection(null)} setScreen={setScreen}/>;
};

/* ---------- Picker ---------- */
const ReportsPicker = ({ onPick }) => {
  const [cls, setCls] = React.useState("XI");
  const [search, setSearch] = React.useState("");

  // Only graded / closed tests can have a class report
  const candidates = window.APP.TESTS
    .filter(t => t.status === "grading" || t.status === "closed")
    .filter(t => t.className === cls)
    .filter(t => !search || t.title.toLowerCase().includes(search.toLowerCase()) || t.id.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="cx-page" style={{ maxWidth: 920 }}>
      <window.AppUI.PageHeader
        eyebrow="Class reports"
        title="Open a class report"
        meta={["Pick the class and test you'd like to review. You'll see how the cohort performed and get a Gemini-drafted lesson plan for the next session."]}
      />

      <window.AppUI.Card title="1 · Class">
        <window.AppUI.Tabs value={cls} onChange={setCls} ariaLabel="Class"
          items={["IX", "X", "XI", "XII"].map(c => ({ value: c, label: `Class ${c}` }))}/>
      </window.AppUI.Card>

      <div className="cx-card flush" style={{ marginTop: 20 }}>
        <div className="cx-card-head" style={{ padding: "18px 22px", margin: 0, gap: 12, flexWrap: "wrap" }}>
          <div className="cx-card-title">2 · Test</div>
          <div className="ui-search" style={{ flex: 1, minWidth: 200 }}>
            <RIcon name="search" size={14}/>
            <input className="input" placeholder="Search tests…" value={search} onChange={e=>setSearch(e.target.value)}/>
          </div>
          <span className="muted" style={{ fontSize: 12.5 }}>{candidates.length} graded</span>
        </div>
        {candidates.length === 0 && (
          <window.AppUI.EmptyState compact icon="report" title="No graded tests"
            hint={`No graded tests for class ${cls} yet. Finish evaluating a test first.`}/>
        )}
        <div className="ui-list" style={{ borderTop: candidates.length ? "1px solid var(--line-soft)" : "none" }}>
          {candidates.map((t) => {
            const pct = t.students ? Math.round(t.reviewed / t.students * 100) : 0;
            return (
              <div key={t.id} onClick={() => onPick({ className: cls, test: t })}
                className="ui-row clickable cx-datarow r5"
                style={{ display: "grid", padding: "14px 22px", gap: 14 }}>
                <span className="ui-id">{t.id}</span>
                <div className="ui-row-main">
                  <div className="ui-row-title">{t.title}</div>
                  <div className="ui-row-sub">{t.subject} · {t.chapter}</div>
                </div>
                <RStatusPill status={t.status} scheduledDate={t.date} isExpired={t.is_expired}/>
                <div style={{ display:"flex", flexDirection:"column", gap: 4 }}>
                  <div className="progress"><div style={{ width: pct + "%", background: t.status === "closed" ? "var(--green)" : "var(--accent)" }}></div></div>
                  <span className="muted tabular" style={{ fontSize: 11.5 }}>{t.reviewed}/{t.students} reviewed</span>
                </div>
                <button className="btn sm primary" style={{ justifySelf:"end" }} onClick={(e)=>{ e.stopPropagation(); onPick({ className: cls, test: t }); }}>
                  Open<RIcon name="arrowRight" size={14}/>
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

/* ---------- Class report view ---------- */
const ClassReportView = ({ selection, onChange, setScreen }) => {
  const { className, test } = selection;
  const totalStudents = test.students || 0;
  const reviewed = test.reviewed || 0;

  // All three lists below are populated from backend aggregates (schema.sql:
  // v_question_accuracy, v_misconception_frequency, lesson_plans + steps).
  const perQ = window.APP.PER_QUESTION_PCT || [];
  const avg = perQ.length ? Math.round(perQ.reduce((a, r) => a + (r.pct || 0), 0) / perQ.length) : null;
  const buckets = window.APP.SCORE_BUCKETS || [];
  const maxBucket = buckets.length ? Math.max(...buckets.map(b => b.count)) : 0;
  const misconceptions = window.APP.TOP_MISCONCEPTIONS || [];
  const lessonPlan = window.APP.LESSON_PLAN || [];

  const st = test.stats || {};
  return (
    <div className="cx-page" style={{ maxWidth: 1280 }}>
      <window.AppUI.PageHeader
        onBack={onChange} backLabel="Change selection"
        eyebrow={`Class ${className} · ${test.subject}`}
        title={test.title}
        status={<RStatusPill status={test.status} scheduledDate={test.date} isExpired={test.is_expired}/>}
        meta={[<span className="mono">{test.id}</span>, test.chapter, test.date, `${reviewed}/${totalStudents} reviewed`]}
        actions={<>
          <button className="btn"><RIcon name="download" size={15}/>Download PDF</button>
          <button className="btn primary"><RIcon name="sparkle" size={15}/>Share with HoD</button>
        </>}
      />

      {/* Summary stats — backend supplies avg/high/low/above/need on test.stats */}
      <div className="cx-card">
        <window.AppUI.StatRow flush items={[
          { value: st.avg, label: "class average", tone: "blue" },
          { value: st.high, label: "highest", tone: "green" },
          { value: st.low, label: "lowest", tone: "red" },
          { value: st.abovePassing, label: "above passing", tone: "green" },
          { value: st.needAttention, label: "need attention", tone: "amber" },
        ]}/>
      </div>

      <div className="cx-catalog-split" style={{ marginTop: 20, gap: 20 }}>
        {/* Per-question accuracy */}
        <window.AppUI.Card title="Per-question accuracy" action={<span className="muted" style={{ fontSize: 12 }}>full · partial · missed</span>}>
          <div style={{ display:"flex", flexDirection:"column", gap: 12 }}>
            {perQ.length === 0 && <div className="muted" style={{ fontSize: 13 }}>No graded questions yet.</div>}
            {perQ.map(({q, pct, fullMarks, partial, missed}) => (
              <div key={q.id} style={{ display:"flex", alignItems:"center", gap: 12 }}>
                <span className="mono" style={{ color:"var(--accent)", width: 32, fontSize: 12.5, fontWeight: 600 }}>Q{q.num}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ color:"var(--ink-1)", fontSize: 13, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{q.english}</div>
                  <div style={{ display:"flex", height: 6, background:"var(--track)", borderRadius: 999, overflow:"hidden", marginTop: 6 }}>
                    <div style={{ width: `${fullMarks/totalStudents*100}%`, background:"var(--green)" }}></div>
                    <div style={{ width: `${partial/totalStudents*100}%`, background:"var(--accent)" }}></div>
                    <div style={{ width: `${missed/totalStudents*100}%`, background:"var(--red)" }}></div>
                  </div>
                </div>
                <span className="tabular" style={{ width: 50, textAlign:"right", color: pct > 75 ? "var(--green)" : pct > 50 ? "var(--accent)" : "var(--red)", fontSize: 14, fontWeight: 600 }}>{pct}%</span>
              </div>
            ))}
          </div>
        </window.AppUI.Card>

        {/* Score distribution */}
        <window.AppUI.Card title="Score distribution">
          {buckets.length === 0 && <div className="muted" style={{ fontSize: 13, padding:"6px 0" }}>No distribution data yet.</div>}
          <div style={{ display:"flex", alignItems:"flex-end", gap: 10, height: 160, padding:"10px 4px 4px" }}>
            {buckets.map(b => (
              <div key={b.label} style={{ flex: 1, display:"flex", flexDirection:"column", alignItems:"center", gap: 4, height: "100%", justifyContent: "flex-end" }}>
                <span className="tabular" style={{ fontSize: 12, color:"var(--ink-1)", fontWeight: 600 }}>{b.count}</span>
                <div style={{ width:"100%", height: `${b.count/maxBucket*100}%`, background: b.color, borderRadius:"6px 6px 2px 2px", minHeight: 4 }}></div>
                <span className="muted mono" style={{ fontSize: 10.5 }}>{b.label}</span>
              </div>
            ))}
          </div>
          <div className="muted" style={{ fontSize: 12, marginTop: 10, textAlign:"center" }}>Percentage band · {totalStudents} students</div>
        </window.AppUI.Card>
      </div>

      {/* Misconceptions */}
      <window.AppUI.Card style={{ marginTop: 20 }} title="Top misconceptions across the cohort"
        action={<span className="muted" style={{ fontSize: 12 }}>detected by Gemini · ranked by student count</span>}>
        {misconceptions.length === 0 && <div className="muted" style={{ fontSize: 13 }}>No misconceptions detected yet.</div>}
        <div className="ui-list">
          {misconceptions.map(m => (
            <window.AppUI.ListRow key={m.code}
              leading={<span className="pill violet">{m.code}</span>}
              title={m.concept}
              status={<span className="pill grey mono">{m.trend}</span>}
              amount={`${m.n} students`}/>
          ))}
        </div>
      </window.AppUI.Card>

      {/* Lesson plan */}
      <div className="cx-card" style={{ marginTop: 20 }}>
        <div className="cx-card-head">
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span style={{ color:"var(--accent)", display: "inline-flex" }}><RIcon name="sparkle" size={16}/></span>
            <span className="cx-card-title">Suggested lesson plan · next session</span>
            <span className="pill grey mono">gemini-2.5-flash</span>
          </div>
          <span className="muted" style={{ fontSize: 12 }}>targets the top 3 gaps · 50 min</span>
        </div>
        {lessonPlan.length === 0 && <div className="muted" style={{ fontSize: 13 }}>Lesson plan will be generated once evaluations are confirmed.</div>}
        <div className="ui-list">
          {lessonPlan.map((row, i) => (
            <div key={i} className="ui-row" style={{ alignItems: "flex-start", gap: 14 }}>
              <span className="mono" style={{ color:"var(--accent)", fontSize: 12, minWidth: 100, paddingTop: 2 }}>{row.time}</span>
              <div className="ui-row-main">
                <div className="ui-row-title" style={{ fontWeight: 500, lineHeight: 1.5, whiteSpace: "normal" }}>{row.activity}</div>
                <div style={{ marginTop: 6 }}><span className="pill violet">{row.focus}</span></div>
              </div>
            </div>
          ))}
        </div>
        <div className="cx-card-foot" style={{ justifyContent: "space-between", flexWrap: "wrap" }}>
          <span className="muted" style={{ fontSize: 12.5 }}>Regenerate with different constraints (time, mode, group size).</span>
          <span style={{ display:"flex", gap: 8 }}>
            <button className="btn sm"><RIcon name="refresh" size={14}/>Regenerate</button>
            <button className="btn sm"><RIcon name="copy" size={14}/>Copy</button>
            <button className="btn sm primary"><RIcon name="calendar" size={14}/>Send to calendar</button>
          </span>
        </div>
      </div>
    </div>
  );
};

// Kept for compatibility: a single KPI tile in the new .cx-stat look.
const StatCard = ({ label, value, color }) => (
  <div className="cx-card cx-stat">
    <div className="cx-stat-label">{label}</div>
    <div className="cx-stat-value tabular" style={{ color }}>{value}</div>
  </div>
);

window.ClassReports = ClassReports;
