// AdminFacilityDetail.jsx — F1. The facility detail sub-app: header with a
// Pause/Resume action (routed through ConfirmAction, never a toast) and eight
// tabs (Overview, Margin accounts, Claims, Policy, Access control, DDF & reserve,
// Modules, Liquidation). Charts are inline SVG/CSS, dependency-free, mock.
//
// Reuses: HeroStrip/SupportKPI/SectionHeader/AdminStatus (AdminWidgets),
// Icon/StatusPill/MonoAddr/Eyebrow (Primitives), fmtMoney/fmtMoneyShort,
// fmtDate (AdminPrimitives). Read-only tabs in P1; grant/revoke (F6), DDF
// reconciliation (F9) and the rate simulator (F10) are follow-up.

const DETAIL_TABS = ["Overview", "Margin accounts", "Claims", "Policy", "Access control", "DDF & reserve", "Modules", "Liquidation"];

// ── small building blocks ────────────────────────────────────────────────
const FDCard = ({ title, children, action }) => (
  <section className="card" style={{ padding: 0 }}>
    {title && (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "var(--space-8)", padding: "var(--space-16) var(--space-20)", borderBottom: "1px solid var(--border)" }}>
        <h3 style={{ margin: 0, font: '600 16px/20px "Figtree", sans-serif', color: "var(--fg)", letterSpacing: "-0.005em" }}>{title}</h3>
        {action}
      </div>
    )}
    <div style={{ padding: "var(--space-20)" }}>{children}</div>
  </section>
);

const KV = ({ label, value, tone }) => (
  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "var(--space-12)", padding: "var(--space-12) 0", borderTop: "1px solid var(--border)" }}>
    <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{label}</span>
    <span className="tnum" style={{ font: '500 13px/18px "Inter", sans-serif', color: tone || "var(--fg)", textAlign: "right" }}>{value}</span>
  </div>
);

// Horizontal value bars (collateral breakdown)
const HBars = ({ rows }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-12)" }}>
    {rows.length === 0 && <div style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>No collateral posted.</div>}
    {rows.map((r, i) => (
      <div key={i}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "var(--space-4)" }}>
          <span style={{ font: '500 12px/16px "Inter", sans-serif', color: "var(--fg)" }}>{r.token}</span>
          <span className="tnum" style={{ font: '500 12px/16px "Inter", sans-serif', color: "var(--fg-muted)" }}>{fmtMoneyShort(r.value)}</span>
        </div>
        <div style={{ height: 6, borderRadius: "var(--radius-sm)", background: "var(--black-10)", overflow: "hidden" }}>
          <div style={{ width: `${r.pct}%`, height: "100%", background: ["var(--accent)", "var(--success)", "var(--gold-60)", "var(--fg-subtle)"][i % 4], borderRadius: "var(--radius-sm)" }} />
        </div>
      </div>
    ))}
  </div>
);

// Vertical bars (utilization over time / accounts by status)
const VBars = ({ data, max = 100, fmt }) => {
  const peak = Math.max(max, ...data.map((d) => d.value || 0), 1);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: "var(--space-8)", height: 120, paddingTop: "var(--space-8)" }}>
      {data.map((d, i) => (
        <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: "var(--space-8)", minWidth: 0 }}>
          <div style={{ font: '500 10px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }} className="tnum">{fmt ? fmt(d.value) : d.value}</div>
          <div style={{ width: "100%", maxWidth: 34, height: `${(d.value / peak) * 80}px`, minHeight: 2, background: d.color || "var(--accent)", borderRadius: "3px 3px 0 0" }} />
          <div style={{ font: '400 10px/14px "Inter", sans-serif', color: "var(--fg-subtle)", whiteSpace: "nowrap" }}>{d.label || d.day}</div>
        </div>
      ))}
    </div>
  );
};

const ScopedTh = ({ children, align = "left" }) => (
  <span style={{ display: "inline-flex", justifyContent: align === "right" ? "flex-end" : "flex-start", font: '500 11px/16px "Inter", sans-serif', letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-subtle)" }}>{children}</span>
);

// ── the detail ─────────────────────────────────────────────────────────--
const AdminFacilityDetail = ({ facility, onBack, onNavigate, onAction, roles, state, onRetry }) => {
  const [tab, setTab] = React.useState("Overview");
  const [grantOpen, setGrantOpen] = React.useState(false);
  const [grantRole, setGrantRole] = React.useState("OPERATOR");
  const [grantAddr, setGrantAddr] = React.useState("");
  const [grantLabel, setGrantLabel] = React.useState("");
  const [ddfTab, setDdfTab] = React.useState("Reserve overview");
  const [simType, setSimType] = React.useState("Borrow more");
  const [simAmount, setSimAmount] = React.useState("");
  if (state === "loading") return <PageSkeleton shape="dashboard" />;
  if (state === "error") return <PageError title="Couldn't load the facility" onRetry={onRetry} />;
  if (!facility) return <PageError title="No facility selected" onRetry={onBack} />;

  const d = buildFacilityDetail(facility);
  const claims = (window.ADMIN_CLAIMS || []).filter((c) => c.facility === facility.name);

  const pauseAction = facility.status === "paused"
    ? { key: "unpause-facility", label: "Resume facility", icon: "play", bg: "var(--accent)", fg: "var(--white-100)" }
    : facility.status === "shutdown"
      ? null
      : { key: "pause-facility", label: "Pause facility", icon: "pause", bg: "var(--gold-60)", fg: "var(--white-100)" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
      {/* Header */}
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
        <button className="btn btn--text btn--sm" type="button" onClick={onBack} style={{ alignSelf: "flex-start" }}>
          <Icon name="arrow" size={13} stroke={1.6} style={{ transform: "rotate(180deg)" }} /> Back to facilities
        </button>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "var(--space-16)", flexWrap: "wrap" }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-12)" }}>
              <h1 style={{ margin: 0, font: '700 28px/32px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>{facility.name}</h1>
              <AdminStatus status={facility.status} />
            </div>
            <div style={{ marginTop: "var(--space-8)", font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              Collaterals: {d.config.collateralTokens.join(", ")} · Settlements: {d.config.settlementTokens.join(", ")}
            </div>
          </div>
          {pauseAction && (
            <button type="button" onClick={() => onAction(pauseAction.key, facility)} style={{
              height: 38, padding: "0 var(--space-16)", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer",
              background: pauseAction.bg, color: pauseAction.fg, font: '600 13px "Inter", sans-serif',
              display: "inline-flex", alignItems: "center", gap: "var(--space-8)",
            }}><Icon name={pauseAction.icon} size={14} stroke={1.7} /> {pauseAction.label}</button>
          )}
        </div>
      </div>

      {/* Tab bar */}
      <div style={{ display: "flex", gap: "var(--space-2)", borderBottom: "1px solid var(--border)", overflowX: "auto" }}>
        {DETAIL_TABS.map((t) => (
          <button key={t} type="button" onClick={() => setTab(t)} style={{
            all: "unset", cursor: "pointer", padding: "var(--space-12) var(--space-16)", whiteSpace: "nowrap",
            font: '500 13px/18px "Inter", sans-serif',
            color: tab === t ? "var(--accent)" : "var(--fg-subtle)",
            borderBottom: tab === t ? "2px solid var(--accent)" : "2px solid transparent", marginBottom: -1,
          }}>{t}</button>
        ))}
      </div>

      {/* ── Overview ── */}
      {tab === "Overview" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
          <HeroStrip
            hero={{ label: "Total collateral", value: fmtMoneyShort(d.kpis.totalCollateral), sub: `${d.kpis.activeAccounts} accounts in this facility` }}
            supports={[
              { label: "Total borrowed", value: fmtMoneyShort(d.kpis.totalBorrowed), sub: `${d.config.utilization.toFixed(1)}% utilization` },
              { label: "Interest rate", value: `${d.config.interestRate.toFixed(1)}%`, sub: "Borrow APR" },
              { label: "At risk", value: d.kpis.warn + d.kpis.default, sub: `${d.kpis.warn} warn · ${d.kpis.default} default`, tone: d.kpis.default ? "danger" : d.kpis.warn ? "warning" : undefined },
            ]}
          />
          <FDCard title="Facility configuration">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 32px" }}>
              <KV label="Collateral tokens" value={d.config.collateralTokens.join(", ")} />
              <KV label="Settlement tokens" value={d.config.settlementTokens.join(", ")} />
              <KV label="Interest rate" value={`${d.config.interestRate.toFixed(1)}%`} />
              <KV label="Liquidation threshold" value={`${d.config.liqThreshold}%`} />
              <KV label="Max LTV" value={`${d.config.maxLTV}%`} />
              <KV label="Pool TVL" value={fmtMoneyShort(d.config.poolTVL)} />
              <KV label="Utilization" value={`${d.config.utilization.toFixed(1)}%`} />
              <KV label="Total borrowed" value={fmtMoneyShort(d.config.totalBorrowed)} />
            </div>
          </FDCard>
          <div style={{ font: '400 11px/16px "Inter", sans-serif', color: "var(--fg-faint)" }}>Charts are mock and refresh in-memory only.</div>
          <div className="dash-cols" style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0,1fr))", gap: "var(--space-16)" }}>
            <FDCard title="Collateral breakdown"><HBars rows={d.charts.collateralBreakdown} /></FDCard>
            <FDCard title="Utilization over time"><VBars data={d.charts.utilization7d} fmt={(v) => `${v}%`} /></FDCard>
            <FDCard title="Accounts by status"><VBars data={d.charts.accountsByStatus} max={Math.max(1, ...d.charts.accountsByStatus.map((s) => s.count))} fmt={() => ""} /></FDCard>
          </div>
        </div>
      )}

      {/* ── Margin accounts (scoped) ── */}
      {tab === "Margin accounts" && (
        <FDCard title={`Margin accounts (${d.accounts.length})`}>
          <div className="adm-scroll">
            <div style={{ display: "grid", gridTemplateColumns: "120px 1fr 1fr 90px 110px", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
              <ScopedTh>Account</ScopedTh><ScopedTh align="right">Collateral</ScopedTh><ScopedTh align="right">Borrowed</ScopedTh><ScopedTh align="right">HF</ScopedTh><ScopedTh>Status</ScopedTh>
            </div>
            {d.accounts.length === 0 ? <div style={{ padding: "var(--space-16) 0", color: "var(--fg-subtle)", font: '400 13px "Inter", sans-serif' }}>No accounts in this facility.</div> :
              d.accounts.map((a) => (
                <button key={a.id} type="button" onClick={() => onNavigate && onNavigate("account-detail", a)} style={{
                  all: "unset", cursor: "pointer", display: "grid", gridTemplateColumns: "120px 1fr 1fr 90px 110px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)", width: "100%", boxSizing: "border-box",
                }} onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                  <span className="addr" style={{ font: '500 13px "JetBrains Mono", monospace', color: "var(--accent)" }}>{a.id}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.collateral)}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.borrowed)}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '600 13px "Inter", sans-serif', color: a.hf === 0 ? "var(--fg-faint)" : a.hf < 1.2 ? "var(--danger)" : a.hf < 1.5 ? "var(--gold-70)" : "var(--success)" }}>{a.hf === 0 ? "—" : a.hf.toFixed(2)}</span>
                  <span><AdminStatus status={a.status} /></span>
                </button>
              ))}
          </div>
        </FDCard>
      )}

      {/* ── Claims (scoped, read-only) ── */}
      {tab === "Claims" && (
        <FDCard title={`Claims (${claims.length})`} action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Manage on the Claims page</span>}>
          <div className="adm-scroll">
            <div style={{ display: "grid", gridTemplateColumns: "90px 1.2fr 1.4fr 130px", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
              <ScopedTh>Case</ScopedTh><ScopedTh>Type</ScopedTh><ScopedTh>Investor</ScopedTh><ScopedTh>Status</ScopedTh>
            </div>
            {claims.length === 0 ? <div style={{ padding: "var(--space-16) 0", color: "var(--fg-subtle)", font: '400 13px "Inter", sans-serif' }}>No claims for this facility.</div> :
              claims.map((c) => (
                <div key={c.caseId} style={{ display: "grid", gridTemplateColumns: "90px 1.2fr 1.4fr 130px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)" }}>
                  <span className="addr" style={{ font: '500 12px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{c.caseId}</span>
                  <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg)" }}>{c.type}</span>
                  <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.investor}</span>
                  <span><AdminStatus status={c.status} /></span>
                </div>
              ))}
          </div>
        </FDCard>
      )}

      {/* ── Policy ── */}
      {tab === "Policy" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <FDCard title="Identity registry" action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Shared with {d.policy.sharedWith} facilities</span>}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
              The Identity Registry encodes who may use this facility. Claim topics and trusted issuers are bound at deploy. Read-only; to change, redeploy.
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "0 24px" }}>
              <KV label="Bound registry" value={d.policy.registry} />
              <KV label="Jurisdiction" value={d.policy.jurisdiction} />
              <KV label="Trusted issuer" value={d.policy.trustedIssuer} />
            </div>
          </FDCard>
          <FDCard title="Claim requirements" action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>From IR · ClaimTopicsRegistry</span>}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-12)" }}>
              Every claim topic a wallet must carry on its ONCHAINID to use this facility. Regulated (KYC, accreditation) and Ascend-specific custom claims are enforced through the same registry.
            </div>
            {d.policy.claimTopics.map((t, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "var(--space-12)", padding: "var(--space-12) 0", borderTop: "1px solid var(--border)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)" }}>
                  <span style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{t.name}</span>
                  <span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{t.kind}</span>
                </div>
                <StatusPill variant="healthy" dot={false}>Required</StatusPill>
              </div>
            ))}
          </FDCard>
          <FDCard title="Compliance module" action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Runtime gate</span>}>
            <div style={{ display: "flex", alignItems: "baseline", gap: "var(--space-12)", marginBottom: "var(--space-12)" }}>
              <span style={{ font: '600 14px "Inter", sans-serif', color: "var(--fg)" }}>{d.policy.complianceModule.name}</span>
              <span className="addr" style={{ font: '400 12px "JetBrains Mono", monospace', color: "var(--fg-subtle)" }}>{d.policy.complianceModule.addr}</span>
            </div>
            <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-12)" }}>Evaluated on every borrow, deposit, withdraw, and transfer. Bound at deploy; to change, redeploy.</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 24px" }}>
              {d.policy.complianceModule.rules.map((r, i) => (
                <KV key={i} label={r.label} value={r.value} />
              ))}
            </div>
          </FDCard>
        </div>
      )}

      {/* ── Access control (grant/revoke via ConfirmAction, F6) ── */}
      {tab === "Access control" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: "var(--space-12)", flexWrap: "wrap" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 620 }}>
              Onchain role membership for this credit facility. Grant and revoke are signed by the connected admin wallet and recorded in the audit log.
            </div>
            {!grantOpen && <button className="btn btn--primary btn--sm" type="button" onClick={() => setGrantOpen(true)}><Icon name="plus" size={12} stroke={1.8} /> Grant role</button>}
          </div>
          {grantOpen && (
            <FDCard title="Grant role">
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr 1fr", gap: "var(--space-16)" }}>
                <div>
                  <div style={{ font: '500 12px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Role</div>
                  <select value={grantRole} onChange={(e) => setGrantRole(e.target.value)} style={{ width: "100%", height: 38, padding: "0 var(--space-12)", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 13px "Inter", sans-serif' }}>
                    {(roles || d.roles).map((r) => <option key={r.role} value={r.role}>{r.role}</option>)}
                  </select>
                </div>
                <div>
                  <div style={{ font: '500 12px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Address</div>
                  <input value={grantAddr} onChange={(e) => setGrantAddr(e.target.value)} placeholder="0x…" style={{ width: "100%", height: 38, padding: "0 var(--space-12)", boxSizing: "border-box", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 13px "JetBrains Mono", monospace' }} />
                </div>
                <div>
                  <div style={{ font: '500 12px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Label (optional)</div>
                  <input value={grantLabel} onChange={(e) => setGrantLabel(e.target.value)} placeholder="e.g. Ops Lead" style={{ width: "100%", height: 38, padding: "0 var(--space-12)", boxSizing: "border-box", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 13px "Inter", sans-serif' }} />
                </div>
              </div>
              <div style={{ display: "flex", gap: "var(--space-8)", marginTop: "var(--space-16)" }}>
                <button className="btn btn--secondary" type="button" onClick={() => { setGrantOpen(false); setGrantAddr(""); setGrantLabel(""); }}>Cancel</button>
                <button className="btn btn--primary" type="button" disabled={!grantAddr.trim()} style={{ opacity: grantAddr.trim() ? 1 : 0.5 }}
                  onClick={() => { if (!grantAddr.trim()) return; onAction("grant-role", { role: grantRole, addr: grantAddr.trim(), label: grantLabel.trim(), facility: facility.name }); setGrantOpen(false); setGrantAddr(""); setGrantLabel(""); }}>Grant role</button>
              </div>
            </FDCard>
          )}
          {(roles || d.roles).map((r) => (
            <FDCard key={r.role} title={r.role} action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{r.members.length} member{r.members.length === 1 ? "" : "s"}</span>}>
              <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-12)" }}>{r.desc}</div>
              <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 90px", gap: "var(--space-16)", padding: "0 0 var(--space-8)", borderBottom: "1px solid var(--border)" }}>
                <ScopedTh>Address</ScopedTh><ScopedTh>Label</ScopedTh><ScopedTh>Granted</ScopedTh><ScopedTh align="right">Action</ScopedTh>
              </div>
              {r.members.length === 0 ? <div style={{ padding: "var(--space-12) 0", color: "var(--fg-subtle)", font: '400 13px "Inter", sans-serif' }}>No members.</div> :
                r.members.map((m, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 90px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                  <span className="addr" style={{ font: '500 12px "JetBrains Mono", monospace', color: "var(--fg)" }}>{m.addr}</span>
                  <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{m.label}</span>
                  <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{fmtDate(m.granted)}</span>
                  <div style={{ display: "flex", justifyContent: "flex-end" }}>
                    <button className="btn btn--secondary btn--sm" type="button" style={{ color: "var(--danger)" }} onClick={() => onAction("revoke-role", { role: r.role, addr: m.addr, facility: facility.name })}>Revoke</button>
                  </div>
                </div>
              ))}
            </FDCard>
          ))}
        </div>
      )}

      {/* ── DDF & reserve (sub-tabs + reconciliation export, F9) ── */}
      {tab === "DDF & reserve" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <div style={{ display: "flex", gap: "var(--space-2)", borderBottom: "1px solid var(--border)", overflowX: "auto" }}>
            {["Reserve overview", "Active auctions", "Resolution records", "Reconciliation"].map((st) => (
              <button key={st} type="button" onClick={() => setDdfTab(st)} style={{
                all: "unset", cursor: "pointer", padding: "var(--space-8) var(--space-12)", whiteSpace: "nowrap",
                font: '500 12px/16px "Inter", sans-serif',
                color: ddfTab === st ? "var(--accent)" : "var(--fg-subtle)",
                borderBottom: ddfTab === st ? "2px solid var(--accent)" : "2px solid transparent", marginBottom: -1,
              }}>{st}</button>
            ))}
          </div>

          {ddfTab === "Reserve overview" && (
            <HeroStrip
              hero={{ label: "Total reserve", value: fmtMoneyShort(d.ddf.reserve.total), sub: "Pool capacity" }}
              supports={[
                { label: "Committed", value: fmtMoneyShort(d.ddf.reserve.committed), sub: `${d.ddf.reserve.utilization}% utilized` },
                { label: "Available", value: fmtMoneyShort(d.ddf.reserve.available), sub: "Healthy" },
                { label: "Active auctions", value: d.ddf.activeAuctions.length, sub: "In this facility" },
              ]}
            />
          )}

          {ddfTab === "Active auctions" && (
            <FDCard title="Active auctions">
              <div className="adm-scroll">
                <div style={{ display: "grid", gridTemplateColumns: "110px 110px 1fr 1fr 70px 110px 110px", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
                  <ScopedTh>Auction</ScopedTh><ScopedTh>Account</ScopedTh><ScopedTh align="right">Current bid</ScopedTh><ScopedTh align="right">Reserve</ScopedTh><ScopedTh align="right">Bids</ScopedTh><ScopedTh>Time</ScopedTh><ScopedTh>Status</ScopedTh>
                </div>
                {d.ddf.activeAuctions.map((a) => (
                  <div key={a.id} style={{ display: "grid", gridTemplateColumns: "110px 110px 1fr 1fr 70px 110px 110px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)" }}>
                    <span className="addr" style={{ font: '500 12px "JetBrains Mono", monospace', color: "var(--fg)" }}>{a.id}</span>
                    <span className="addr" style={{ font: '400 12px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{a.account}</span>
                    <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.bid)}</span>
                    <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.reserve)}</span>
                    <span className="tnum" style={{ textAlign: "right", font: '400 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{a.bids}</span>
                    <span className="tnum" style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-muted)" }}>{a.time}</span>
                    <span><span className="chip chip--info" style={{ padding: "var(--space-2) var(--space-8)", fontSize: 11 }}>{a.status}</span></span>
                  </div>
                ))}
              </div>
            </FDCard>
          )}

          {ddfTab === "Resolution records" && (
            <FDCard title="Resolution records">
              <div className="adm-scroll">
                <div style={{ display: "grid", gridTemplateColumns: "110px 110px 110px 1fr 1fr 1fr 100px", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
                  <ScopedTh>Auction</ScopedTh><ScopedTh>Account</ScopedTh><ScopedTh>Status</ScopedTh><ScopedTh align="right">Reserve advance</ScopedTh><ScopedTh align="right">Proceeds</ScopedTh><ScopedTh align="right">Variance</ScopedTh><ScopedTh>Final</ScopedTh>
                </div>
                {d.ddf.resolutionRecords.map((r) => (
                  <div key={r.auction} style={{ display: "grid", gridTemplateColumns: "110px 110px 110px 1fr 1fr 1fr 100px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)" }}>
                    <span className="addr" style={{ font: '500 12px "JetBrains Mono", monospace', color: "var(--fg)" }}>{r.auction}</span>
                    <span className="addr" style={{ font: '400 12px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{r.account}</span>
                    <span><AdminStatus status={r.auctionStatus === "settled" ? "executed" : "pending"} /></span>
                    <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(r.reserveAdvance)}</span>
                    <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(r.proceeds)}</span>
                    <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: r.variance > 0 ? "var(--success)" : "var(--fg-muted)" }}>{fmtMoney(r.variance)}</span>
                    <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-muted)", textTransform: "capitalize" }}>{r.finalStatus}</span>
                  </div>
                ))}
              </div>
            </FDCard>
          )}

          {ddfTab === "Reconciliation" && (
            <FDCard title="Reserve reconciliation" action={<button className="btn btn--secondary btn--sm" type="button" onClick={() => window.downloadCSV(`ddf-reconciliation-${facility.id}.csv`, ["Auction", "Account", "Auction status", "Reserve advance", "Proceeds", "Variance", "Final status"], d.ddf.resolutionRecords.map((r) => [r.auction, r.account, r.auctionStatus, r.reserveAdvance, r.proceeds, r.variance, r.finalStatus]))}><Icon name="download" size={13} stroke={1.6} /> Export report</button>}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "var(--space-16)" }}>
                <div><div className="stat-label" style={{ fontSize: 11 }}>Expected replenishment</div><div className="tnum" style={{ font: '600 20px/26px "Inter", sans-serif', color: "var(--fg)", marginTop: "var(--space-4)" }}>{fmtMoneyShort(d.ddf.reconciliation.expectedReplenishment)}</div></div>
                <div><div className="stat-label" style={{ fontSize: 11 }}>Actual proceeds</div><div className="tnum" style={{ font: '600 20px/26px "Inter", sans-serif', color: "var(--fg)", marginTop: "var(--space-4)" }}>{fmtMoneyShort(d.ddf.reconciliation.actualProceeds)}</div></div>
                <div><div className="stat-label" style={{ fontSize: 11 }}>Variance</div><div className="tnum" style={{ font: '600 20px/26px "Inter", sans-serif', color: "var(--success)", marginTop: "var(--space-4)" }}>+{fmtMoneyShort(d.ddf.reconciliation.variance)}</div></div>
              </div>
            </FDCard>
          )}
        </div>
      )}

      {/* ── Modules (read-only; whitelist mgmt = F4) ── */}
      {tab === "Modules" && (
        <FDCard title="Configured modules" action={<button className="btn btn--secondary btn--sm" type="button" onClick={() => onNavigate && onNavigate("module-management")}>Manage modules <Icon name="arrow" size={12} stroke={1.6} /></button>}>
          <div className="adm-scroll">
            <div style={{ display: "grid", gridTemplateColumns: "1.4fr 110px 150px 2fr", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
              <ScopedTh>Name</ScopedTh><ScopedTh>Type</ScopedTh><ScopedTh>Chain address</ScopedTh><ScopedTh>Description</ScopedTh>
            </div>
            {d.modules.map((m, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "1.4fr 110px 150px 2fr", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)" }}>
                <span style={{ font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{m.name}</span>
                <span><span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{m.type}</span></span>
                <span className="addr" style={{ font: '400 12px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{m.addr}</span>
                <span style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{m.desc}</span>
              </div>
            ))}
          </div>
        </FDCard>
      )}

      {/* ── Liquidation (scoped queue + rate-impact simulator, F10) ── */}
      {tab === "Liquidation" && (
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
        <FDCard title={`At-risk & default queue (${d.liquidationQueue.length})`} action={<span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>DDF auto-triggered by searchers</span>}>
          <div className="adm-scroll">
            <div style={{ display: "grid", gridTemplateColumns: "110px 140px 1fr 1fr 90px 140px 110px", gap: "var(--space-16)", padding: "0 0 var(--space-12)", borderBottom: "1px solid var(--border)" }}>
              <ScopedTh>Account</ScopedTh><ScopedTh>Wallet</ScopedTh><ScopedTh align="right">Collateral</ScopedTh><ScopedTh align="right">Debt</ScopedTh><ScopedTh align="right">HF</ScopedTh><ScopedTh>Resolution</ScopedTh><ScopedTh>Time</ScopedTh>
            </div>
            {d.liquidationQueue.length === 0 ? <div style={{ padding: "var(--space-16) 0", color: "var(--fg-subtle)", font: '400 13px "Inter", sans-serif' }}>No at-risk positions in this facility.</div> :
              d.liquidationQueue.map((p) => (
                <div key={p.id} style={{ display: "grid", gridTemplateColumns: "110px 140px 1fr 1fr 90px 140px 110px", gap: "var(--space-16)", padding: "var(--space-12) 0", alignItems: "center", borderTop: "1px solid var(--border)" }}>
                  <span className="addr" style={{ font: '500 13px "JetBrains Mono", monospace', color: "var(--fg)" }}>{p.id}</span>
                  <span className="addr" style={{ font: '400 12px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{p.wallet}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(p.collateral)}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(p.debt)}</span>
                  <span className="tnum" style={{ textAlign: "right", font: '600 13px "Inter", sans-serif', color: p.hf < 1.0 ? "var(--danger)" : "var(--gold-70)" }}>{p.hf.toFixed(2)}</span>
                  <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-muted)", textTransform: "capitalize" }}>{p.resolution.replace(/-/g, " ")}</span>
                  <span className="tnum" style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-muted)" }}>{p.timeInDefault}</span>
                </div>
              ))}
          </div>
        </FDCard>
        {(() => {
          const reserveFactor = 0.15;
          const curU = facility.utilization;
          const tvl = facility.tvl || 1;
          const borrowed = tvl * curU / 100;
          const baseRate = facility.rate * 0.25;
          const slope1 = (facility.rate - baseRate) / Math.max(curU, 1);
          const slope2 = slope1 * 4;
          const borrowRate = (u) => (u <= curU ? baseRate + slope1 * u : facility.rate + slope2 * (u - curU));
          const lenderAPY = (u) => borrowRate(u) * (u / 100) * (1 - reserveFactor);
          const amt = Math.max(0, parseFloat(simAmount) || 0);
          let projU = curU;
          if (amt > 0) {
            projU = simType === "Borrow more"
              ? Math.min(100, (borrowed + amt) / tvl * 100)
              : Math.min(100, borrowed / Math.max(1, tvl - amt) * 100);
          }
          const W = 600, H = 120, maxR = Math.max(borrowRate(100), 1);
          const line = (fn) => Array.from({ length: 21 }, (_, i) => { const u = i * 5; return `${(u / 100 * W).toFixed(1)},${(H - fn(u) / maxR * H).toFixed(1)}`; }).join(" ");
          const Stat = ({ label, value, tone }) => (
            <div><div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{label}</div><div className="tnum" style={{ font: '600 16px/22px "Inter", sans-serif', color: tone || "var(--fg)", marginTop: "var(--space-2)" }}>{value}</div></div>
          );
          return (
            <FDCard title="Liquidity rate impact simulator">
              <div style={{ display: "flex", alignItems: "flex-end", gap: "var(--space-20)", flexWrap: "wrap", marginBottom: "var(--space-20)" }}>
                <div>
                  <div style={{ font: '500 12px/16px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Simulation type</div>
                  <SegmentControl value={simType} onChange={setSimType} options={[{ value: "Borrow more", label: "Borrow more" }, { value: "Withdraw liquidity", label: "Withdraw liquidity" }]} />
                </div>
                <div>
                  <div style={{ font: '500 12px/16px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>Amount ({d.config.settlementTokens[0]})</div>
                  <input value={simAmount} onChange={(e) => setSimAmount(e.target.value)} placeholder="0" style={{ width: 200, height: 38, padding: "0 var(--space-12)", boxSizing: "border-box", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 14px "Inter", sans-serif' }} />
                </div>
              </div>
              <div className="dash-cols" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-16)" }}>
                <div style={{ padding: "var(--space-16) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-lg)", display: "flex", gap: "var(--space-24)" }}>
                  <div style={{ font: '600 11px/16px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-subtle)", writingMode: "horizontal-tb" }}>Current</div>
                  <Stat label="Utilization" value={`${curU.toFixed(1)}%`} />
                  <Stat label="Borrow rate" value={`${borrowRate(curU).toFixed(2)}%`} />
                  <Stat label="Lender APY" value={`${lenderAPY(curU).toFixed(2)}%`} />
                </div>
                <div style={{ padding: "var(--space-16) var(--space-16)", background: amt > 0 ? "var(--blue-10)" : "var(--bg-alt)", borderRadius: "var(--radius-lg)", display: "flex", gap: "var(--space-24)" }}>
                  <div style={{ font: '600 11px/16px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-subtle)" }}>Projected</div>
                  {amt > 0 ? (
                    <React.Fragment>
                      <Stat label="Utilization" value={`${projU.toFixed(1)}%`} tone={projU > 90 ? "var(--danger)" : projU > 80 ? "var(--gold-70)" : undefined} />
                      <Stat label="Borrow rate" value={`${borrowRate(projU).toFixed(2)}%`} />
                      <Stat label="Lender APY" value={`${lenderAPY(projU).toFixed(2)}%`} />
                    </React.Fragment>
                  ) : <div style={{ alignSelf: "center", font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Enter an amount to see projected impact.</div>}
                </div>
              </div>
              <div style={{ marginTop: "var(--space-20)" }}>
                <div style={{ font: '500 11px/16px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>Interest rate curve</div>
                <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="150" preserveAspectRatio="none" style={{ display: "block", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
                  <polyline points={line(borrowRate)} fill="none" stroke="var(--accent)" strokeWidth="2.5" />
                  <polyline points={line(lenderAPY)} fill="none" stroke="var(--success)" strokeWidth="2.5" />
                  <line x1={curU / 100 * W} y1="0" x2={curU / 100 * W} y2={H} stroke="var(--fg-faint)" strokeWidth="1.5" strokeDasharray="4 4" />
                  {amt > 0 && <line x1={projU / 100 * W} y1="0" x2={projU / 100 * W} y2={H} stroke="var(--gold-60)" strokeWidth="2" />}
                </svg>
                <div style={{ display: "flex", gap: "var(--space-20)", marginTop: "var(--space-12)", alignItems: "center", flexWrap: "wrap" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: "var(--space-8)", font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}><span style={{ width: 14, height: 2.5, background: "var(--accent)" }} /> Borrow rate</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: "var(--space-8)", font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}><span style={{ width: 14, height: 2.5, background: "var(--success)" }} /> Lender APY</span>
                  <span style={{ font: '400 11px "Inter", sans-serif', color: "var(--fg-faint)", marginLeft: "auto" }}>Simulation only. No actual transaction will be executed.</span>
                </div>
              </div>
            </FDCard>
          );
        })()}
        </div>
      )}
    </div>
  );
};

window.AdminFacilityDetail = AdminFacilityDetail;
