/* ==================================================================
   Overview → 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.APP.CURRENT_USER;
  const school = window.APP.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 type="button" className="btn primary" onClick={() => setScreen("announcements")}>
            <CX.Icon name="plus" size={15}/> 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={<CX.Tag>Today</CX.Tag>}
              />

              <CX.StatCard
                icon="building" color="var(--blue-solid)" label="Students enrolled"
                value={CX.num(d.students.total)}
                onAction={() => setScreen("students")}
                actionLabel="Open students"
                footNote={`${CX.num(d.students.boarders)} boarders · ${CX.num(d.students.dayScholars)} day scholars`}
                action={<CX.Tag>Roster</CX.Tag>}
              />

              {/* 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={<CX.Tag>Ledger</CX.Tag>}
                />
              ) : (
                <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>
                <CX.CardHead
                  title="Enrolment by wing"
                  sub={`${CX.num(d.students.boarders)} boarders · ${CX.num(d.students.dayScholars)} day scholars`}
                />
                <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
                  <div>
                    <div className="cx-stat-value">{CX.num(d.students.total)}</div>
                    <div className="ui-stat-label">students</div>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 12.5 }}>
                    {d.wings.map((w) => (
                      <div key={w.key} style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--ink-2)" }}>
                        <span style={{ width: 8, height: 8, borderRadius: "50%", background: w.color, flexShrink: 0 }}/>
                        <span>{w.label}</span>
                        <span style={{ marginLeft: "auto", paddingLeft: 10, color: "var(--ink-0)", fontWeight: 500, fontVariantNumeric: "tabular-nums" }}>
                          {CX.num(w.students)}
                        </span>
                      </div>
                    ))}
                  </div>
                </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`,
                }))}/>
                <CX.CardFoot
                  note="Wings group the school's classes by level"
                  action="Academics" onAction={() => setScreen("academics")}
                />
              </CX.Card>

              <CX.Card>
                <CX.CardHead title="Staff check-in" right={<CX.Tag>Today</CX.Tag>}/>
                <div style={{ display: "flex", justifyContent: "center", marginBottom: 12 }}>
                  <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, marginTop: 12, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                  {[
                    { 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)", fontVariantNumeric: "tabular-nums" }}>{r.n}/{d.staff.total}</span>
                      </div>
                      <CX.Meter 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={16}/></div>
                    <div>Check-ins come from the Teacher 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 className="ui-section-label" style={{ paddingTop: 14, borderTop: "1px solid var(--line)" }}>Upcoming</div>
                <div className="ui-list">
                  {(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 (
                      <window.AppUI.ListRow
                        key={i}
                        leading={
                          <div style={{
                            width: 38, height: 38, borderRadius: "var(--radius-ctl)", flexShrink: 0,
                            border: "1px solid var(--line)", background: "var(--bg-2)",
                            display: "flex", flexDirection: "column", alignItems: "center",
                            justifyContent: "center", lineHeight: 1, position: "relative",
                          }}>
                            <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-0)", fontVariantNumeric: "tabular-nums" }}>{dt.getDate()}</span>
                            <span style={{ fontSize: 9, fontWeight: 500, color: "var(--ink-3)", letterSpacing: "0.04em", marginTop: 2 }}>
                              {dt.toLocaleDateString("en-IN", { month: "short" }).toUpperCase()}
                            </span>
                            <span style={{ position: "absolute", top: -2, right: -2, width: 8, height: 8, borderRadius: "50%", background: e.color, border: "2px solid var(--surface)" }}/>
                          </div>
                        }
                        title={e.title}
                        sub={e.sub}
                        status={e.past ? <window.AppUI.StatusBadge tone="grey">Past</window.AppUI.StatusBadge> : null}
                      />
                    );
                  })}
                </div>
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitDashboard = DashScreen;
