// AdminLiquidations.jsx — read-only liquidation monitor. DDF liquidation is
// auto-triggered by searchers; this page observes. C-6: the red HF always
// carries a severity + resolution context, never a naked number.

const RESOLUTION_META = {
  "ddf-eligible": { label: "DDF eligible",     cls: "chip--gold",    action: "Awaiting searcher" },
  "ddf-auction":  { label: "DDF auction active", cls: "chip--info",  action: "DDF active" },
  "monitoring":   { label: "Monitoring",        cls: "chip--neutral", action: "—" },
};

const AdminLiquidations = ({ positions, onNavigate, state, onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load positions" onRetry={onRetry} />;

  const counts = {
    all: positions.length,
    critical: positions.filter(p => p.severity === "critical").length,
    high: positions.filter(p => p.severity === "high").length,
    medium: positions.filter(p => p.severity === "medium").length,
  };
  const totalDebt = positions.reduce((s, p) => s + p.debt, 0);
  const filtered = positions.filter(p =>
    (filter === "all" || p.severity === filter) &&
    (q === "" || p.id.includes(q) || p.facility.toLowerCase().includes(q.toLowerCase()) || p.wallet.includes(q))
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Risk & liquidations" title="Liquidation monitor" icon="gavel"
        lede="Monitor positions at risk across all credit facilities. DDF liquidation is auto-triggered by searchers — this page is read-only."
        annot="C-5 sentence case" />

      <HeroStrip
        hero={{ label: "Debt at risk", value: fmtMoneyShort(totalDebt), sub: `Across ${positions.length} positions below or nearing threshold`, tone: "danger" }}
        supports={[
          { label: "Critical", value: counts.critical, sub: "HF below 1.00 — in default", tone: "danger" },
          { label: "High", value: counts.high, sub: "Approaching liquidation", tone: "warning" },
          { label: "Monitoring", value: counts.medium, sub: "Watched, not yet eligible" },
        ]}
      />

      <div>
        <SectionHeader eyebrow="Positions at risk" title="Positions at risk" count={filtered.length}
          annot="C-6 HF carries severity + resolution"
          action={<SearchBox placeholder="Search by account, wallet, or facility…" value={q} onChange={setQ} width={300} />} />

        <div style={{ marginBottom: 16 }}>
          <SegmentControl value={filter} onChange={setFilter} options={[
            { value: "all", label: "All", count: counts.all },
            { value: "critical", label: "Critical", count: counts.critical },
            { value: "high", label: "High", count: counts.high },
            { value: "medium", label: "Medium", count: counts.medium },
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "110px 1.3fr 140px 1fr 1fr 110px 150px 120px", gap: 14, padding: "10px 20px", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Account</Th><Th>Facility</Th><Th>Wallet</Th>
              <Th align="right" sortable>Collateral</Th><Th align="right" sortable>Debt</Th>
              <Th align="right" sortable>Health</Th><Th>Resolution</Th><Th>Time in default</Th>
            </div>
            {filtered.map((p, i) => {
              const res = RESOLUTION_META[p.resolution];
              const hfColor = p.hf < 1.0 ? "var(--danger)" : "var(--gold-70)";
              return (
                <div key={p.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "110px 1.3fr 140px 1fr 1fr 110px 150px 120px", gap: 14, padding: "14px 20px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                  <span className="addr" style={{ font: '500 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{p.id}</span>
                  <span style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.facility}</span>
                  <span className="addr" style={{ font: '400 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{p.wallet}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(p.collateral)}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(p.debt)}</span>
                  <div style={{ textAlign: "right" }}>
                    <div className="tnum" style={{ font: '600 15px/18px "Inter", sans-serif', color: hfColor }}>{p.hf.toFixed(2)}</div>
                    <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", textTransform: "capitalize" }}>{p.severity}</div>
                  </div>
                  <div>
                    <span className={`chip ${res.cls}`} style={{ padding: "2px 8px" }}>{res.label}</span>
                    <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: 3 }}>{res.action}</div>
                  </div>
                  <span className="tnum" style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{p.timeInDefault}</span>
                </div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
};

window.AdminLiquidations = AdminLiquidations;
