/* ==================================================================
   Admin Cockpit → 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",
                  "Working days in window", "Recorded %"];
    const body = d.rows.map((r) => [
      r.name, r.role, r.subjects || "", r.presentDays, r.leaveDays, 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: "Weekend",    cls: "weekend" },
  ];

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow={`Teaching staff${d ? " · " + d.staffTotal : ""}`}
        title="Staff Attendance"
        onBack={() => setScreen("dashboard")}
        actions={
          <>
            <CX.Seg value={period} onChange={setPeriod} options={[
              { value: "daily", label: "Daily" },
              { value: "monthly", label: "Monthly" },
              { value: "yearly", label: "Yearly" },
            ]}/>
            <button className="cx-btn-dark" onClick={exportCsv} disabled={!d?.rows?.length}>
              <CX.Icon name="download" size={16}/> Export CSV
            </button>
          </>
        }
      />

      <CX.Screen state={state} skeleton={<CX.Skeleton rows={4} height={90}/>}>
        {d && (
          <>
            <div className="cx-grid cols-4" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 20 }}>
              <div className="cx-card tight">
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 6 }}>Teaching staff</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span className="cx-stat-value sm">{CX.num(d.staffTotal)}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-3)" }}>on the roll</span>
                </div>
              </div>
              <div className="cx-card tight">
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 6 }}>Checked in today</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span className="cx-stat-value sm">{CX.num(d.presentToday)}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-3)" }}>of {d.staffTotal}</span>
                </div>
              </div>
              <div className="cx-card tight">
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 6 }}>Days with any data</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span className="cx-stat-value sm">{CX.num(d.daysWithData)}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-3)" }}>in this window</span>
                </div>
              </div>
              <div className="cx-card tight">
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 6 }}>Check-ins recorded</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span className="cx-stat-value sm">{CX.num(d.marksInWindow)}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: d.coverageMeaningful ? "var(--green)" : "var(--amber)" }}>
                    {d.coverageMeaningful ? "usable" : "too sparse to average"}
                  </span>
                </div>
              </div>
            </div>

            {!d.coverageMeaningful && (
              <div className="cx-card" style={{ marginBottom: 20 }}>
                <div className="cx-note">
                  <div className="cx-note-mark"><CX.Icon name="alert" size={18}/></div>
                  <div>
                    <strong style={{ color: "var(--ink-0)" }}>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>
              </div>
            )}

            <CX.Card>
              <div className="cx-card-head" style={{ marginBottom: 6 }}>
                <div className="cx-card-title">
                  {period === "daily" ? "Last 14 days" : period === "monthly" ? "Last 31 days" : "Last 12 months (weekly)"}
                </div>
                <div style={{ display: "flex", gap: 16, fontSize: 12.5, color: "var(--ink-2)", 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>

              <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: "13px 0", borderBottom: "1px solid var(--line-soft)",
                    }}>
                      <CX.Avatar name={r.name} size="lg"/>
                      <div className="cx-attwho">
                        <div className="cx-row-title">{r.name}</div>
                        <div className="cx-row-sub" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                          {[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" : CX.title(c.state)
                                }`}/>
                        ))}
                      </div>
                      <span className="cx-attstat">
                        {d.coverageMeaningful
                          ? `${r.recordedPct}%`
                          : `${r.presentDays}/${r.workDays}`}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 14, gap: 12, flexWrap: "wrap" }}>
                <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>
                <span className="cx-pill">Source · teacher check-in app</span>
              </div>
            </CX.Card>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitStaffAttendance = StaffAttendanceScreen;
