/* ==================================================================
   Overview → Staff Attendance
   ------------------------------------------------------------------
   The heat-map from the reference design, driven by teacher_attendance.

   ONE THING TO UNDERSTAND BEFORE READING A NUMBER HERE: rows in
   teacher_attendance are written when a teacher checks in on the mobile
   app. A day with no row therefore means "nothing was recorded", which is
   NOT the same as "absent" — and the backend keeps the two apart
   ('unrecorded' vs 'leave'). This screen never colours an unrecorded day
   red, and it suppresses the headline average entirely when check-in
   coverage is too thin to average honestly. A confident 43% would be a
   lie about people's jobs.
   ================================================================== */

const StaffAttendanceScreen = ({ setScreen }) => {
  const CX = window.CX;
  const [period, setPeriod] = useState("monthly");
  const state = CX.useCockpitData(`/admin/cockpit/staff-attendance?period=${period}`);
  const d = state.data;

  const exportCsv = () => {
    if (!d) return;
    const head = ["Name", "Role", "Subjects", "Days present", "Days on leave",
                  "Holidays", "Working days in window", "Recorded %"];
    const body = d.rows.map((r) => [
      r.name, r.role, r.subjects || "", r.presentDays, r.leaveDays, r.holidayDays ?? 0,
      r.workDays, `${r.recordedPct}%`,
    ]);
    CX.exportCsv(`staff-attendance-${period}.csv`, [head, ...body]);
  };

  const LEGEND = [
    { label: "Present",    cls: "present" },
    { label: "On leave",   cls: "leave" },
    { label: "No record",  cls: "unrecorded" },
    { label: "Holiday",    cls: "holiday" },
    { label: "Weekend",    cls: "weekend" },
  ];

  return (
    <div className="cx-page">
      <CX.PageHead
        onBack={() => setScreen("dashboard")}
        backLabel="Dashboard"
        eyebrow={`Teaching staff${d ? " · " + d.staffTotal : ""}`}
        title="Staff attendance"
        status={d && (d.coverageMeaningful
          ? <window.AppUI.StatusBadge tone="green" variant="outline">Usable coverage</window.AppUI.StatusBadge>
          : <window.AppUI.StatusBadge tone="amber" variant="outline">Sparse data</window.AppUI.StatusBadge>)}
        actions={
          <button type="button" className="btn primary" onClick={exportCsv} disabled={!d?.rows?.length}>
            <CX.Icon name="download" size={15}/> Export CSV
          </button>
        }
      />

      <div style={{ marginBottom: 20 }}>
        <CX.Seg size="" value={period} onChange={setPeriod} ariaLabel="Attendance period" options={[
          { value: "daily", label: "Daily" },
          { value: "monthly", label: "Monthly" },
          { value: "yearly", label: "Yearly" },
        ]}/>
      </div>

      <CX.Screen state={state} skeleton={<CX.Skeleton rows={4} height={90}/>}>
        {d && (
          <>
            <CX.Card style={{ marginBottom: 20 }}>
              <window.AppUI.StatRow flush align="left" items={[
                { value: CX.num(d.staffTotal), label: "Teaching staff on the roll" },
                { value: CX.num(d.presentToday), label: `Checked in today · of ${d.staffTotal}`, tone: d.presentToday ? "green" : undefined },
                { value: CX.num(d.daysWithData), label: "Days with any data in this window" },
                {
                  value: CX.num(d.marksInWindow),
                  label: <>Check-ins recorded · <span style={{ color: d.coverageMeaningful ? "var(--green)" : "var(--amber)", fontWeight: 500 }}>
                    {d.coverageMeaningful ? "usable" : "too sparse to average"}</span></>,
                },
              ]}/>
            </CX.Card>

            {!d.coverageMeaningful && (
              <div className="ui-alert amber" style={{ marginBottom: 20, display: "flex", gap: 10, alignItems: "flex-start" }}>
                <CX.Icon name="alert" size={16} style={{ flexShrink: 0, marginTop: 2 }}/>
                <div>
                  <strong>Attendance percentages are hidden for this window.</strong>{" "}
                  Only {d.marksInWindow} check-in{d.marksInWindow === 1 ? " has" : "s have"} been recorded across {d.rows.length} staff,
                  so any average would describe app adoption rather than who came to work.
                  Days with no record are drawn as outlines below — never as absences.
                </div>
              </div>
            )}

            <CX.Card>
              <CX.CardHead
                style={{ marginBottom: 6 }}
                title={period === "daily" ? "Last 14 days" : period === "monthly" ? "Last 31 days" : "Last 12 months (weekly)"}
                right={
                  <div style={{ display: "flex", gap: 14, fontSize: 12.5, color: "var(--ink-3)", alignItems: "center", flexWrap: "wrap" }}>
                    {LEGEND.map((l) => (
                      <span key={l.cls} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <span className={`cx-heat ${l.cls}`} style={{ width: 10, height: 10, borderRadius: 3 }}/>
                        {l.label}
                      </span>
                    ))}
                  </div>
                }
              />

              <div className="cx-tablescroll cx-attscroll">
                <div className="cx-attgrid">
                  {d.rows.length === 0 && (
                    <CX.Empty icon="staff" title="No teaching staff on the roll"
                              hint="Add teachers under Academics → Teachers."/>
                  )}
                  {d.rows.map((r) => (
                    <div key={r.id} className="cx-attrow" style={{
                      padding: "12px 0", borderBottom: "1px solid var(--line)",
                    }}>
                      <window.AppUI.Avatar name={r.name} className="cx-av"/>
                      <div className="cx-attwho">
                        <div className="ui-row-title">{r.name}</div>
                        <div className="ui-row-sub">
                          {[r.role, r.subjects].filter(Boolean).join(" · ")}
                        </div>
                      </div>
                      <div className="cx-attcells">
                        {r.cells.map((c, i) => (
                          <span key={i}
                                className={`cx-heat ${c.state}${c.date === d.today ? " today" : ""}`}
                                title={`${CX.date(c.date, { day: "numeric", month: "short" })} · ${
                                  c.state === "unrecorded" ? "No check-in recorded"
                                  : c.state === "holiday" ? `Holiday — ${c.holiday}` : CX.title(c.state)
                                }`}/>
                        ))}
                      </div>
                      <span className="cx-attstat" style={{ fontVariantNumeric: "tabular-nums" }}>
                        {d.coverageMeaningful
                          ? `${r.recordedPct}%`
                          : `${r.presentDays}/${r.workDays}`}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="cx-card-foot" style={{ flexWrap: "wrap", borderTop: 0, marginTop: 4 }}>
                <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                  {d.rows.length} staff · {d.coverageMeaningful
                    ? "percentage is days present ÷ working days in window"
                    : "showing days present ÷ working days, not a percentage"}
                </span>
                <CX.Tag>Source · teacher check-in app</CX.Tag>
              </div>
            </CX.Card>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitStaffAttendance = StaffAttendanceScreen;
