/* ==================================================================
   Admin Cockpit → Finance
   ------------------------------------------------------------------
   The school's finance system ("the Ledger" / easyaccounts) surfaced in
   the cockpit for the first time. It is a SEPARATE Postgres database on
   port 5432, read through a read-only pool — see backend db/ledger.ts.

   Because it is a separate deployment it may simply not be running. That
   is an ordinary state, not an error: the whole screen becomes one
   "not connected" card that says which knob to turn, and no tile ever
   prints a zero that could be mistaken for "collected nothing".

   READ-ONLY BY DESIGN. Nothing here writes to the finance system; the
   book of record stays in the Ledger's own app.
   ================================================================== */

const FinanceScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state = CX.useCockpitData("/admin/cockpit/finance", { pollMs: 300000 });
  const d = state.data;

  const COMPONENT_COLOR = {
    TUITION: "var(--green-solid)", TRANSPORT: "var(--blue-solid)",
    HOSTEL: "var(--pink-solid)", READMISSION: "var(--amber-solid)",
    SECURITY: "var(--violet-solid)",
  };

  const exportCsv = () => {
    if (!d?.connected) return;
    CX.exportCsv("fee-collection-by-month.csv", [
      ["Month", "Receipts", "Amount (INR)"],
      ...d.collection.byMonth.map((m) => [m.month, m.n, m.amount]),
    ]);
  };

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Ledger · finance system"
        title="Finance"
        actions={d?.connected && (
          <button className="cx-btn-dark" onClick={exportCsv}>
            <CX.Icon name="download" size={16}/> Export collection
          </button>
        )}
      />

      <CX.Screen state={state} skeleton={<CX.Skeleton rows={3} height={190}/>}>
        {d && !d.connected && (
          <CX.NotConnected
            title="Finance system not connected"
            what="The Ledger database (easyaccounts) isn't reachable from this backend, so fee, payroll and asset figures can't be read."
            why="It is a separate Postgres — locally on port 5432. Start it, or point the backend at it with LEDGER_PGHOST / LEDGER_PGPORT / LEDGER_PGDATABASE."
          />
        )}

        {d?.connected && (
          <>
            {/* ---- Headline tiles ---- */}
            <div className="cx-grid cols-3" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
              <CX.StatCard
                icon="rupee" color="var(--green-solid)" label="Collected This Month"
                value={CX.money(d.collection.thisMonth)}
                delta={d.collection.deltaPct != null
                  ? `${d.collection.deltaPct >= 0 ? "↑" : "↓"} ${Math.abs(d.collection.deltaPct)}%`
                  : null}
                deltaTone={d.collection.deltaPct >= 0 ? "up" : "down"}
                footNote={`${CX.money(d.collection.lastMonth)} last month · ${CX.money(d.collection.today)} today`}
                action={<span className="cx-pill">Live</span>}
              />
              <CX.StatCard
                icon="wallet" color="var(--blue-solid)" label="Collected All Time"
                value={CX.money(d.collection.allTime)}
                delta={`${CX.num(d.collection.payments)} receipts`}
                deltaTone="flat"
                footNote={d.collection.since ? `since ${CX.date(d.collection.since, { day: "numeric", month: "short", year: "numeric" })}` : ""}
                action={<span className="cx-pill">{d.students.active} active students</span>}
              />
              <CX.StatCard
                icon="box" color="var(--pink-solid)" label="Assets on Register"
                value={CX.num(d.assets.total)}
                delta={CX.money(d.assets.value)}
                deltaTone="flat"
                footNote={`${d.assets.inUse} in use · ${d.assets.inStock} in stock`}
                action={<span className="cx-pill">Register</span>}
              />
            </div>

            {/* ---- Trend · mix ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1.3fr 1fr", marginBottom: 20 }}>
              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">Collection Trend</div>
                  <span className="cx-pill">Last 8 months</span>
                </div>
                <div style={{ fontSize: 42, fontWeight: 600, letterSpacing: "-2px", color: "var(--ink-0)" }}>
                  {CX.money(d.collection.byMonth.reduce((a, m) => a + m.amount, 0))}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 18 }}>
                  {CX.num(d.collection.byMonth.reduce((a, m) => a + m.n, 0))} receipts in the window
                </div>
                <div style={{ display: "flex", alignItems: "flex-end", gap: 10, height: 170 }}>
                  {d.collection.byMonth.map((m) => (
                    <div key={m.month} style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", height: "100%", minWidth: 0 }}
                         title={`${m.month}: ${CX.money(m.amount, { full: true })} across ${m.n} receipts`}>
                      <div style={{
                        height: `${Math.max(6, m.heightPct)}%`,
                        background: "var(--green-solid)", borderRadius: 12,
                        opacity: 0.35 + 0.65 * (m.heightPct / 100),
                      }}/>
                    </div>
                  ))}
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
                  {d.collection.byMonth.map((m) => (
                    <div key={m.month} style={{
                      flex: 1, textAlign: "center", fontSize: 11, fontWeight: 600,
                      color: "var(--ink-4)", minWidth: 0, overflow: "hidden",
                    }}>
                      {new Date(m.month + "-01T00:00:00").toLocaleDateString("en-IN", { month: "short" }).toUpperCase()}
                    </div>
                  ))}
                </div>
                <div className="cx-card-foot">
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    Read-only view of the Ledger · the finance app remains the book of record
                  </span>
                </div>
              </CX.Card>

              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">Collection Mix</div>
                  <span className="cx-pill">By head</span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 14, marginBottom: 20 }}>
                  {d.collection.byComponent.map((c) => {
                    const share = d.collection.allTime
                      ? Math.round((c.amount / d.collection.allTime) * 100) : 0;
                    return (
                      <div key={c.component || "other"}>
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, marginBottom: 7 }}>
                          <span style={{ fontWeight: 600, color: "var(--ink-0)" }}>
                            {CX.title(c.component || "Other")}
                          </span>
                          <span style={{ color: "var(--ink-3)" }}>
                            <strong style={{ color: "var(--ink-0)" }}>{CX.money(c.amount)}</strong> · {c.n}
                          </span>
                        </div>
                        <CX.Meter pct={share} color={COMPONENT_COLOR[c.component] || "var(--grey-solid)"}/>
                      </div>
                    );
                  })}
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-3)", marginBottom: 10 }}>PAYMENT MODE</div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {d.collection.byMode.map((m) => (
                    <span key={m.mode} className="cx-pill">
                      {CX.title(m.mode || "Other")} · {CX.num(m.n)}
                    </span>
                  ))}
                </div>
              </CX.Card>
            </div>

            {/* ---- Entities · payables · payroll ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1.2fr 1fr" }}>
              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">By Institution</div>
                  <span className="cx-pill">{d.entities.length} entities</span>
                </div>
                {d.entities.length === 0 ? (
                  <CX.Empty icon="building" title="No entities configured"/>
                ) : d.entities.map((e) => (
                  <div key={e.name} className="cx-row">
                    <div className="cx-av" style={{
                      background: e.color || "var(--bg-2)",
                      color: e.color ? "#fff" : "var(--ink-2)",
                    }}>{(e.shortName || e.name || "?").slice(0, 3).toUpperCase()}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="cx-row-title">{e.name}</div>
                      <div className="cx-row-sub">{CX.num(e.students)} active student(s)</div>
                    </div>
                    <span style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink-0)", whiteSpace: "nowrap" }}>
                      {CX.money(e.collected)}
                    </span>
                  </div>
                ))}
                <div className="cx-card-foot">
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    {CX.num(d.students.withUid)} of {CX.num(d.students.total)} Ledger students carry a portal UID
                  </span>
                </div>
              </CX.Card>

              <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
                <CX.Card>
                  <div className="cx-card-head">
                    <div className="cx-card-title">Payables &amp; Payroll</div>
                    {d.payables.unpaid > 0
                      ? <span className="cx-pill tint amber">{d.payables.unpaid} unpaid</span>
                      : <span className="cx-pill tint green">Settled</span>}
                  </div>
                  <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
                    <div className="cx-tile" style={{ flex: 1 }}>
                      <div className="cx-tile-value">{CX.money(d.payables.unpaidAmount)}</div>
                      <div className="cx-tile-label">Unpaid vendor bills</div>
                    </div>
                    <div className="cx-tile" style={{ flex: 1 }}>
                      <div className="cx-tile-value">{CX.money(d.payroll.amount)}</div>
                      <div className="cx-tile-label">Salary paid this year</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    {d.payables.bills} bill(s) on record · {d.payroll.payments} salary payment(s) ·{" "}
                    {d.payroll.employees} active employee(s)
                  </div>
                </CX.Card>

                <CX.Card>
                  <div className="cx-card-head">
                    <div className="cx-card-title">Account Balances</div>
                    <span className="cx-pill">{d.accounts.length} accounts</span>
                  </div>
                  {d.accounts.length === 0 ? (
                    <CX.Empty icon="wallet" title="No accounts configured"/>
                  ) : (
                    // Capped rather than scrolled: a scroll container inside a
                    // card clips its last row mid-height and reads as broken.
                    <div>
                      {d.accounts.slice(0, 6).map((a, i) => (
                        <div key={i} className="cx-row" style={{ padding: "10px 0" }}>
                          <span className="cx-pill grey tint" style={{ flexShrink: 0 }}>{a.type}</span>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{
                              fontSize: 13.5, fontWeight: 500, color: "var(--ink-0)",
                              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                            }}>{a.name}</div>
                          </div>
                          <span style={{
                            fontSize: 14, fontWeight: 700, whiteSpace: "nowrap",
                            color: a.balance < 0 ? "var(--red)" : "var(--ink-0)",
                          }}>{CX.money(a.balance)}</span>
                        </div>
                      ))}
                      {d.accounts.length > 6 && (
                        <div style={{ fontSize: 13, color: "var(--ink-3)", paddingTop: 12 }}>
                          +{d.accounts.length - 6} more account(s) in the Ledger
                        </div>
                      )}
                    </div>
                  )}
                </CX.Card>
              </div>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitFinance = FinanceScreen;
