/* ==================================================================
   Overview → Academics
   ------------------------------------------------------------------
   Master data at a glance: teaching staff, the student roll broken down
   by class, the class/section/subject registry, and how far syllabus
   mapping has actually got.

   Reads /admin/cockpit/academics. Every count comes from the Cockpit
   database; nothing here is illustrative.
   ================================================================== */

const AcademicsScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state = CX.useCockpitData("/admin/cockpit/academics");
  const d = state.data;

  const AcBadge = window.AppUI.StatusBadge;
  const AcRow = window.AppUI.ListRow;
  const statusPill = (s) =>
    s === "present"  ? <AcBadge tone="green">Present</AcBadge>
  : s === "on_leave" ? <AcBadge tone="amber">On leave</AcBadge>
  :                    <AcBadge tone="grey">No record</AcBadge>;

  const WING_COLOR = {
    primary: "var(--pink-solid)", middle: "var(--blue-solid)", senior: "var(--green-solid)",
  };

  // Card title row with a tinted icon tile, like the KPI tiles.
  const iconHead = (icon, color, title, sub, onOpen, openLabel) => (
    <div className="cx-card-head">
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <div className="cx-stat-icon" style={{ background: `color-mix(in srgb, ${color} 14%, transparent)`, color }}>
          <CX.Icon name={icon} size={16}/>
        </div>
        <div style={{ minWidth: 0 }}>
          <div className="cx-card-title">{title}</div>
          <div className="cx-card-sub">{sub}</div>
        </div>
      </div>
      <window.AppUI.IconButton icon="arrowUpRight" label={openLabel} onClick={onOpen} className="sm" size={15}/>
    </div>
  );

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow={`Master data${window.APP.CURRENT_SCHOOL?.academic_year ? " · " + window.APP.CURRENT_SCHOOL.academic_year : ""}`}
        title="Academics"
        actions={
          <button type="button" className="btn primary" onClick={() => setScreen("students")}>
            <CX.Icon name="plus" size={15}/> Manage students
          </button>
        }
      />

      <CX.Screen state={state} skeleton={<CX.Skeleton rows={2} height={320}/>}>
        {d && (
          <>
            {/* ---- Teachers · Students ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1.2fr 1fr", marginBottom: 20 }}>
              <CX.Card>
                {iconHead("staff", "var(--green-solid)", "Teachers",
                  `${CX.num(d.teachers.total)} active`
                  + (d.teachers.pending ? ` · ${d.teachers.pending} pending approval` : "")
                  + (d.teachers.inactive ? ` · ${d.teachers.inactive} inactive` : ""),
                  () => setScreen("teachers"), "Open teachers")}

                <div className="ui-list">
                  {d.teachers.list.length === 0 && (
                    <CX.Empty icon="staff" title="No teaching staff yet"
                              hint="Add teachers from Academics → Teachers."/>
                  )}
                  {d.teachers.list.map((t) => (
                    <AcRow key={t.id}
                      leading={<window.AppUI.Avatar name={t.name}/>}
                      title={t.name}
                      sub={[t.role, t.subjects, t.classes].filter(Boolean).join(" · ") || "No assignments"}
                      status={statusPill(t.status)}
                    />
                  ))}
                </div>

                <CX.CardFoot
                  note={d.teachers.pendingResets
                    ? `${d.teachers.pendingResets} password reset request${d.teachers.pendingResets === 1 ? "" : "s"} waiting`
                    : "No password reset requests"}
                  action={`View all ${CX.num(d.teachers.total)}`}
                  onAction={() => setScreen("teachers")}
                />
              </CX.Card>

              <CX.Card style={{ display: "flex", flexDirection: "column" }}>
                {iconHead("cap", "var(--blue-solid)", "Students",
                  `${CX.num(d.students.total)} enrolled`,
                  () => setScreen("students"), "Open students")}

                {/* Suppressed by the API when it equals the whole roll (a
                    bulk import), so the third figure falls back to section count. */}
                <window.AppUI.StatRow flush items={[
                  { value: CX.num(d.students.boarders), label: "Boarders" },
                  { value: CX.num(d.students.dayScholars), label: "Day scholars" },
                  d.students.newThisTerm != null
                    ? { value: CX.num(d.students.newThisTerm), label: "New in 90 days" }
                    : { value: CX.num(d.classes.sectionCount), label: "Sections" },
                ]}/>

                <div className="ui-section-label" style={{ margin: "20px 0 12px", paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                  By class
                </div>
                <div style={{ flex: 1 }}>
                  <CX.BarList items={d.students.byClass.map((c) => ({
                    label: c.level,
                    pct: c.barPct,
                    value: CX.num(c.students),
                    color: WING_COLOR[c.wing],
                  }))}/>
                </div>
              </CX.Card>
            </div>

            {/* ---- Classes & subjects · syllabus ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1fr 1.2fr" }}>
              <CX.Card>
                <CX.CardHead
                  title="Classes & subjects"
                  right={<CX.Tag>{d.classes.classCount} classes · {d.classes.sectionCount} sections</CX.Tag>}
                />
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginBottom: 20 }}>
                  {d.classes.rows.map((c) => (
                    <div key={c.level} className="cx-tile" style={{ padding: 12, textAlign: "center" }}
                         title={`${c.students} students · sections ${c.sectionLabels || "—"}`}>
                      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink-0)" }}>{c.level}</div>
                      <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>
                        {c.sections} section{c.sections === 1 ? "" : "s"}
                      </div>
                    </div>
                  ))}
                </div>
                <div className="ui-section-label" style={{ marginBottom: 10 }}>
                  {d.subjects.count} subjects
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {d.subjects.list.map((s) => (
                    <AcBadge key={s.id} tone="grey">{s.name}</AcBadge>
                  ))}
                  {d.subjects.count === 0 && (
                    <span style={{ fontSize: 13, color: "var(--ink-3)" }}>No subjects registered yet.</span>
                  )}
                </div>
                <CX.CardFoot
                  note="Registry drives every test-creation picker"
                  action="Manage" onAction={() => setScreen("taxonomy")}
                />
              </CX.Card>

              <CX.Card>
                <CX.CardHead title="Chapters & topics" right={<CX.Tag>Syllabus mapping</CX.Tag>}/>
                {d.syllabus.length === 0 ? (
                  <CX.Empty icon="book" title="No chapters registered"
                            hint="Add them under Academics → Chapters."/>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    {d.syllabus.map((s, i) => {
                      const colors = ["var(--green-solid)", "var(--blue-solid)", "var(--pink-solid)",
                                      "var(--amber-solid)", "var(--violet-solid)", "var(--grey-solid)"];
                      return (
                        <div key={i}>
                          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, marginBottom: 7, gap: 12 }}>
                            <span style={{ fontWeight: 500, color: "var(--ink-0)", minWidth: 0 }}>
                              {s.subject}{s.classLevel ? ` · ${s.classLevel}` : ""}
                            </span>
                            <span style={{ color: "var(--ink-3)", whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                              {s.chapters} chapters · {s.topics} topics ·{" "}
                              <strong style={{ color: "var(--ink-0)", fontWeight: 600 }}>{s.coveragePct}%</strong>
                            </span>
                          </div>
                          <CX.Meter pct={s.coveragePct} color={colors[i % colors.length]}/>
                        </div>
                      );
                    })}
                  </div>
                )}
                <div className="cx-note" style={{ marginTop: 18 }}>
                  <div className="cx-note-mark"><CX.Icon name="book" size={16}/></div>
                  <div>Coverage is the share of a subject's chapters that have at least one topic registered against them — it is what the AI question generator reads when building a paper.</div>
                </div>
                <CX.CardFoot
                  note="Chapters feed test authoring and topic tagging"
                  action="Open registry" onAction={() => setScreen("chapters")}
                />
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitAcademics = AcademicsScreen;
