/* ==================================================================
   Admin Cockpit → Dashboard
   ------------------------------------------------------------------
   The landing screen. Three headline tiles, then enrolment by wing, the
   staff check-in ring, and the school calendar.

   Every figure is read from the two live databases — the Cockpit's own
   Postgres and the Ledger (finance) — via /admin/cockpit/dashboard and
   /admin/cockpit/finance. Where a subsystem has recorded nothing, the tile
   says so rather than printing a zero that reads like a measurement.
   ================================================================== */

const DashScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state  = CX.useCockpitData("/admin/cockpit/dashboard", { pollMs: 120000 });
  const money  = CX.useCockpitData("/admin/cockpit/finance",   { pollMs: 300000 });
  const [monthOffset, setMonthOffset] = useState(0);

  const d = state.data;
  const user = window.KX.CURRENT_USER;
  const school = window.KX.CURRENT_SCHOOL;

  const firstName = user?.name?.split(/\s+/)[0];
  const hour = new Date().getHours();
  const partOfDay = hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
  const dateLabel = new Date().toLocaleDateString("en-IN", {
    weekday: "long", day: "numeric", month: "long", year: "numeric",
  }).toUpperCase();

  const fin = money.data;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow={`${dateLabel}${school?.name ? " · " + school.name : ""}`}
        title={firstName ? `Good ${partOfDay}, ${firstName}` : `Good ${partOfDay}`}
        actions={
          <button className="cx-btn-dark" onClick={() => setScreen("announcements")}>
            <CX.Icon name="plus" size={17}/> New announcement
          </button>
        }
      />

      <CX.Screen state={state}>
        {d && (
          <>
            {/* ---- Headline tiles ---- */}
            <div className="cx-grid cols-3" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
              <CX.StatCard
                icon="staff" color="var(--green-solid)" label="Teaching Staff"
                value={CX.num(d.staff.total)}
                delta={d.staff.joinedRecently ? `↑ ${d.staff.joinedRecently} in 90 days` : null}
                deltaTone="up"
                onAction={() => setScreen("staff-attendance")}
                actionLabel="Open staff attendance"
                footNote={
                  d.staff.checkInsRecorded
                    ? `${d.staff.present} present · ${d.staff.onLeave} on leave · ${d.staff.unmarked} unmarked`
                    : `${d.staff.onLeave} on approved leave · no check-ins recorded today`
                }
                action={<span className="cx-pill">Today</span>}
              />

              <CX.StatCard
                icon="building" color="var(--blue-solid)" label="Hostel Occupancy"
                value={CX.num(d.hostel.allocated)}
                suffix={`/ ${CX.num(d.hostel.beds)} beds`}
                delta={d.hostel.overdue ? `${d.hostel.overdue} outpass overdue` : null}
                deltaTone="warn"
                onAction={() => setScreen("hostel")}
                actionLabel="Open hostel"
                footNote={
                  `${d.hostel.outNow} out now · ${d.hostel.infirmaryActive} in infirmary · ` +
                  `${d.hostel.disciplineOpen} discipline open`
                }
                action={<span className="cx-pill">Gate live</span>}
              />

              {/* Finance is a separate deployment; the tile carries its own
                  connection state rather than silently showing nothing. */}
              {money.loading && !fin ? (
                <div className="cx-skel" style={{ borderRadius: "var(--radius-card)", minHeight: 190 }}/>
              ) : fin?.connected ? (
                <CX.StatCard
                  icon="rupee" color="var(--pink-solid)" label="Collected This Month"
                  value={CX.money(fin.collection.thisMonth)}
                  delta={fin.collection.deltaPct != null
                    ? `${fin.collection.deltaPct >= 0 ? "↑" : "↓"} ${Math.abs(fin.collection.deltaPct)}% vs last month`
                    : null}
                  deltaTone={fin.collection.deltaPct >= 0 ? "up" : "down"}
                  onAction={() => setScreen("finance")}
                  actionLabel="Open finance"
                  footNote={`${CX.money(fin.collection.allTime)} all time · ${CX.num(fin.collection.payments)} receipts`}
                  action={<span className="cx-pill">Ledger</span>}
                />
              ) : (
                <CX.NotConnected
                  title="Finance not connected"
                  what="Fee collection lives in the Ledger database, which isn't reachable from here."
                  why="Start the finance Postgres on port 5432, or set LEDGER_PGHOST / LEDGER_PGPORT for the backend."
                />
              )}
            </div>

            {/* ---- Wing enrolment · staff ring · calendar ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1fr 1fr 1.15fr" }}>
              <CX.Card>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
                  <div className="cx-card-title">Enrolment by Wing</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 13 }}>
                    {d.wings.map((w) => (
                      <div key={w.key} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span style={{ width: 18, height: 18, borderRadius: "50%", background: w.color, flexShrink: 0 }}/>
                        <span><strong>{w.label}</strong> · {CX.num(w.students)}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div style={{ fontSize: 42, fontWeight: 600, letterSpacing: "-2px", margin: "6px 0 2px", color: "var(--ink-0)" }}>
                  {CX.num(d.students.total)}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 16 }}>
                  {CX.num(d.students.boarders)} boarders · {CX.num(d.students.dayScholars)} day scholars
                </div>
                <CX.Columns items={d.wings.map((w) => ({
                  label: w.label, value: CX.num(w.students),
                  heightPct: w.heightPct, color: w.color,
                  title: `${w.label}: ${w.students} students`,
                }))}/>
                <div className="cx-card-foot">
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    Primary is Nursery–IV · Middle V–VIII · Senior IX upward
                  </span>
                  <button className="cx-pill" onClick={() => setScreen("academics")}>Academics</button>
                </div>
              </CX.Card>

              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">Staff Check-in</div>
                  <span className="cx-pill">Today</span>
                </div>
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
                  <CX.Donut
                    total={d.staff.total}
                    segments={[
                      { value: d.staff.present, color: "var(--green-solid)" },
                      { value: d.staff.onLeave, color: "var(--amber-solid)" },
                    ]}
                    centreValue={CX.num(d.staff.total)}
                    centreLabel="teaching staff"
                  />
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  {[
                    { label: "Checked in", n: d.staff.present, color: "var(--green-solid)" },
                    { label: "On approved leave", n: d.staff.onLeave, color: "var(--amber-solid)" },
                    { label: "No record today", n: d.staff.unmarked, color: "var(--grey-solid)" },
                  ].map((r) => (
                    <div key={r.label}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 6 }}>
                        <span style={{ fontWeight: 500, color: "var(--ink-0)" }}>{r.label}</span>
                        <span style={{ color: "var(--ink-3)" }}>{r.n}/{d.staff.total}</span>
                      </div>
                      <CX.Meter thin pct={d.staff.total ? (r.n / d.staff.total) * 100 : 0} color={r.color} className="thin"/>
                    </div>
                  ))}
                </div>
                {!d.staff.checkInsRecorded && (
                  <div className="cx-note" style={{ marginTop: 16 }}>
                    <div className="cx-note-mark"><CX.Icon name="clock" size={18}/></div>
                    <div>Check-ins come from the teacher mobile app. Nothing has been recorded for today yet — this is not the same as everyone being absent.</div>
                  </div>
                )}
              </CX.Card>

              <CX.Card>
                <CX.Calendar
                  anchor={d.today} today={d.today}
                  events={d.calendar.events}
                  offset={monthOffset}
                  onMonthChange={setMonthOffset}
                />
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {(d.calendar.upcoming || []).length === 0 && (
                    <CX.Empty icon="file" title="Nothing scheduled"
                              hint="Tests and staff notices with a date will appear here."/>
                  )}
                  {(d.calendar.upcoming || []).map((e, i) => {
                    const dt = new Date(e.date + "T00:00:00");
                    return (
                      <div key={i} style={{
                        display: "flex", alignItems: "center", gap: 12,
                        background: "var(--bg-2)", borderRadius: 14, padding: "10px 12px",
                      }}>
                        <div style={{
                          width: 38, height: 38, borderRadius: 12, background: e.color, color: "#fff",
                          display: "flex", flexDirection: "column", alignItems: "center",
                          justifyContent: "center", lineHeight: 1, flexShrink: 0,
                        }}>
                          <span style={{ fontSize: 14, fontWeight: 700 }}>{dt.getDate()}</span>
                          <span style={{ fontSize: 8.5, fontWeight: 600 }}>
                            {dt.toLocaleDateString("en-IN", { month: "short" }).toUpperCase()}
                          </span>
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{
                            fontSize: 13.5, fontWeight: 600, color: "var(--ink-0)",
                            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                          }}>{e.title}</div>
                          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{e.sub}</div>
                        </div>
                        {e.past && <span className="cx-pill grey tint">Past</span>}
                      </div>
                    );
                  })}
                </div>
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitDashboard = DashScreen;
