// AdminDashboard.jsx — operational overview. Hero hierarchy (C-4): one hero
// metric (Total value locked) + supporting hairline strip, then three preview
// columns that deep-link into the sub-pages.

const PreviewCard = ({ icon, title, meta, onViewAll, children }) => (
  <section className="card" style={{ padding: 0, display: "flex", flexDirection: "column" }}>
    <div style={{ padding: "18px 20px 14px", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 8, borderBottom: "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ color: "var(--fg-muted)" }}><Icon name={icon} size={16} stroke={1.5}/></span>
        <div>
          <div style={{ font: '600 15px/20px "Figtree", sans-serif', color: "var(--fg)", letterSpacing: "-0.005em" }}>{title}</div>
          <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: 1 }}>{meta}</div>
        </div>
      </div>
      <button className="btn btn--text btn--sm" type="button" onClick={onViewAll}>View all <Icon name="arrow" size={12} stroke={1.6}/></button>
    </div>
    <div style={{ display: "flex", flexDirection: "column" }}>{children}</div>
  </section>
);

const AdminDashboard = ({ facilities, accounts, totals, pools, liquidations, claims, onNavigate, state, onRetry }) => {
  if (state === "loading") return <PageSkeleton shape="dashboard" />;
  if (state === "error")   return <PageError title="Couldn't load the dashboard" onRetry={onRetry} />;

  const atRisk = accounts.filter(a => a.hf > 0 && a.hf < 1.5 || a.status === "default").slice(0, 4);
  const activeFacilities = facilities.filter(f => f.status === "active").length;
  const totalTvl = facilities.reduce((s, f) => s + f.tvl, 0);
  const avgHF = totals.avgHF;
  const hfTone = avgHF < 1.2 ? "danger" : avgHF < 1.5 ? "warning" : undefined;
  const poolUtil = (pools.reduce((s, p) => s + p.utilization, 0) / pools.length).toFixed(1);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Overview" title="Dashboard" icon="grid"
        lede="Platform health and operational overview across every credit facility."
        annot="C-5 sentence case" />

      <HeroStrip
        hero={{ label: "Total value locked", value: fmtMoneyShort(totalTvl), sub: `${activeFacilities} active facilities · across ${facilities.length} total` }}
        supports={[
          { label: "Margin accounts", value: totals.total, sub: `${totals.warn} warn · ${totals.frozen} frozen · ${totals.default} default` },
          { label: "Total borrowed", value: fmtMoneyShort(totals.borrowed), sub: `${fmtMoneyShort(totals.collateral)} collateral posted` },
          { label: "Avg health factor", value: avgHF.toFixed(2), sub: hfTone === "danger" ? "Below 1.20 — action required" : "Caution — monitor at-risk accounts", tone: hfTone },
        ]}
      />

      <div className="dash-cols" style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 16 }}>
        {/* Margin accounts — at risk */}
        <PreviewCard icon="accounts" title="Margin accounts"
          meta={`${totals.total} total · ${totals.warn + totals.default} at-risk`}
          onViewAll={() => onNavigate("accounts")}>
          {atRisk.map((a, i) => {
            const tone = a.hf < 1.2 || a.status === "default" ? "var(--danger)" : "var(--gold-70)";
            return (
              <button key={i} onClick={() => onNavigate("accounts")} style={{
                all: "unset", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "space-between",
                gap: 10, padding: "12px 20px", borderTop: i === 0 ? "none" : "1px solid var(--border)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <div style={{ minWidth: 0 }}>
                  <div className="addr" style={{ font: '500 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{a.id}</div>
                  <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.facility}</div>
                </div>
                <div className="tnum" style={{ font: '600 14px/18px "Inter", sans-serif', color: tone, flexShrink: 0 }}>HF {a.hf.toFixed(2)}</div>
              </button>
            );
          })}
        </PreviewCard>

        {/* Credit facilities */}
        <PreviewCard icon="facility" title="Credit facilities"
          meta={`${facilities.length} total · ${activeFacilities} active · ${facilities.filter(f=>f.default>0).length} with defaults`}
          onViewAll={() => onNavigate("facilities")}>
          {[...facilities].sort((a,b)=>b.tvl-a.tvl).slice(0, 4).map((f, i) => (
            <button key={i} onClick={() => onNavigate("facilities")} style={{
              all: "unset", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "space-between",
              gap: 10, padding: "12px 20px", borderTop: i === 0 ? "none" : "1px solid var(--border)",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <div style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.name}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
                <span className="tnum" style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg-muted)" }}>{fmtMoneyShort(f.tvl)}</span>
                <AdminStatus status={f.status} />
              </div>
            </button>
          ))}
        </PreviewCard>

        {/* Stablecoin pools */}
        <PreviewCard icon="bank" title="Stablecoin pools"
          meta={`${pools.length} pools · ${poolUtil}% avg utilization`}
          onViewAll={() => onNavigate("pools")}>
          {[...pools].sort((a,b)=>b.utilization-a.utilization).slice(0, 4).map((p, i) => {
            const tone = p.utilization > 80 ? "var(--gold-70)" : "var(--accent)";
            return (
              <button key={i} onClick={() => onNavigate("pools")} style={{
                all: "unset", cursor: "pointer", display: "flex", flexDirection: "column", gap: 6,
                padding: "12px 20px", borderTop: i === 0 ? "none" : "1px solid var(--border)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
                  <span style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.token} · {p.facility}</span>
                  <span className="tnum" style={{ font: '600 13px/18px "Inter", sans-serif', color: tone, flexShrink: 0 }}>{p.utilization}%</span>
                </div>
                <div style={{ height: 3, background: "var(--black-20)", borderRadius: 2, overflow: "hidden" }}>
                  <div style={{ width: `${p.utilization}%`, height: "100%", background: tone, borderRadius: 2 }} />
                </div>
              </button>
            );
          })}
        </PreviewCard>
      </div>
    </div>
  );
};

window.AdminDashboard = AdminDashboard;
