// adminDetailData.jsx — mock data for the admin detail layer (F1 facility
// detail, F2 deploy wizard, F3 margin-account detail). Loaded AFTER adminData.jsx
// and AdminWidgets.jsx, so ADMIN_ACCOUNTS and fmtMoney are available.
//
//   · buildFacilityDetail(facility) — F1: derives KPIs / charts from the live
//     account rows and attaches the shared policy / roles / modules / DDF
//     template (OZ used one institutional template across facilities).
//   · ADMIN_ACCOUNT_DETAIL — F3 (per-account debt / collateral / schedule).
//   · DEPLOY_WIZARD_OPTIONS — F2 (module / registry / token option lists).

// ── Shared policy template (Renée: ONCHAINID always all-caps) ────────────
const FACILITY_POLICY = {
  registry: "Ascend Default Registry",
  sharedWith: 4,
  jurisdiction: "US",
  trustedIssuer: "Ascend · 0xA5cE…ABcD",
  claimTopics: [
    { name: "KYC verified", kind: "Regulated", required: true },
    { name: "Accredited Investor", kind: "Regulated", required: true },
    { name: "Partner Membership", kind: "Ascend-specific", required: true },
    { name: "Corporate Email Verified", kind: "Ascend-specific", required: true },
  ],
  complianceModule: {
    name: "Standard Institutional Compliance",
    addr: "0xCmp1...Std",
    rules: [
      { label: "Max transactions", value: "5 / 7 days", sub: "Per actor rolling window" },
      { label: "Borrow size", value: "$10,000 to $5,000,000" },
      { label: "Jurisdiction TVL cap", value: "US ≤ 40% of TVL" },
      { label: "Trading window", value: "Mon-Fri · 12:00-22:00 UTC" },
      { label: "Min credit score", value: "650" },
    ],
  },
};

// ── Shared access-control template ───────────────────────────────────────
const FACILITY_ROLES = [
  { role: "ADMIN", desc: "Full configuration authority. Can grant and revoke any role.",
    members: [{ addr: "0xA1b2…aBcD", label: "Deploy signer", granted: "2026-04-10" }] },
  { role: "OPERATOR", desc: "Run-time operations: pause facility, freeze accounts, clawback.",
    members: [
      { addr: "0xB2c3…B0c1", label: "Ops Lead", granted: "2026-04-12" },
      { addr: "0xC3d4…C1d2", label: "—", granted: "2026-04-19" },
    ] },
  { role: "COMPLIANCE_OFFICER", desc: "Approve / reject claim attestations from KYC providers.",
    members: [{ addr: "0xD4e5…D2e3", label: "Compliance Officer", granted: "2026-04-15" }] },
];

// ── F4: module whitelist (lifted to App state for live add / delete) ─────
// Multiple modules of the same type can be whitelisted; a facility deploy
// picks one of each type from this list.
const ADMIN_MODULE_WHITELIST = [
  { id: "mod-auc-batch",  name: "Batch Clearing",                  type: "Auction",    addr: "0xAuc2...Batch",  chainId: 11155111, updated: "2026-01-15" },
  { id: "mod-auc-dutch",  name: "Dutch Auction v2",                type: "Auction",    addr: "0xAuc1...Dutch",  chainId: 11155111, updated: "2026-01-15" },
  { id: "mod-auc-sealed", name: "Sealed Bid",                      type: "Auction",    addr: "0xAuc3...Sealed", chainId: 11155111, updated: "2026-01-15" },
  { id: "mod-cmp-rwa",    name: "Aggressive RWA Compliance",       type: "Compliance", addr: "0xCmp2...RWA",    chainId: 11155111, updated: "2026-02-20" },
  { id: "mod-cmp-trsy",   name: "Conservative Treasury Compliance", type: "Compliance", addr: "0xCmp4...Trsy",  chainId: 11155111, updated: "2026-02-25" },
  { id: "mod-cmp-eu",     name: "EU Qualified Compliance",         type: "Compliance", addr: "0xCmp3...EU",     chainId: 11155111, updated: "2026-02-22" },
  { id: "mod-cmp-std",    name: "Standard Institutional Compliance", type: "Compliance", addr: "0xCmp1...Std",  chainId: 11155111, updated: "2026-02-20" },
  { id: "mod-fee-flat",   name: "Flat Fee v1",                     type: "Fee",        addr: "0xFee2...Flat",   chainId: 11155111, updated: "2026-01-20" },
  { id: "mod-fee-rwa",    name: "RWA Split Fee",                   type: "Fee",        addr: "0xFee3...RWA",    chainId: 11155111, updated: "2026-02-01" },
  { id: "mod-fee-tier",   name: "Tiered Fee v2",                   type: "Fee",        addr: "0xFee1...Tiered", chainId: 11155111, updated: "2026-01-20" },
  { id: "mod-rsk-agr",    name: "Aggressive Growth",               type: "Risk",       addr: "0xRsk1...Agr",    chainId: 11155111, updated: "2026-01-18" },
  { id: "mod-rsk-inst",   name: "Institutional Guardrail",         type: "Risk",       addr: "0xRsk2...Inst",   chainId: 11155111, updated: "2026-01-18" },
  { id: "mod-rsk-std",    name: "Standard Risk v2",                type: "Risk",       addr: "0xRsk3...Std",    chainId: 11155111, updated: "2026-01-18" },
  { id: "mod-val-nav",    name: "NAV Calculator v1",               type: "Valuation",  addr: "0xVal1...NAV",    chainId: 11155111, updated: "2026-01-22" },
  { id: "mod-ora-clink",  name: "Chainlink Core",                  type: "Oracle",     addr: "0xOra1...CLink",  chainId: 11155111, updated: "2026-01-10" },
  { id: "mod-ora-pyth",   name: "Pyth Price Feed",                 type: "Oracle",     addr: "0xOra2...Pyth",   chainId: 11155111, updated: "2026-02-05" },
  { id: "mod-liq-amm",    name: "AMM Pool Router",                 type: "Liquidity",  addr: "0xLiq1...AMM",    chainId: 11155111, updated: "2026-01-28" },
  { id: "mod-liq-idle",   name: "Idle Vault Router",               type: "Liquidity",  addr: "0xLiq2...Idle",   chainId: 11155111, updated: "2026-02-12" },
];

// ── F7: settlement & reserve-reconciliation feed (read-only) ─────────────
const ADMIN_TRANSACTIONS = [
  { id: "tx-5073", kind: "Auction Resolution", target: "ma-5073", facility: "BENJI Growth Facility", status: "settled", desc: "Liquidation auction settled", reserve: 102510, proceeds: 169840, variance: 67330, txHash: "0x50732328…2ee0", date: "2026-03-24T14:30:00Z" },
  { id: "tx-1100", kind: "Auction Resolution", target: "ma-1100", facility: "Institutional Structured Prime", status: "settled", desc: "Liquidation auction settled", reserve: 74800, proceeds: 75600, variance: 800, txHash: "0x11002329…2ee1", date: "2026-03-24T08:30:00Z" },
  { id: "tx-1160", kind: "Auction Resolution", target: "ma-1160", facility: "Institutional Structured Prime", status: "settled", desc: "Liquidation auction settled", reserve: 87550, proceeds: 96560, variance: 9010, txHash: "0x1160232a…2ee2", date: "2026-03-24T02:30:00Z" },
  { id: "tx-2103", kind: "Auction Resolution", target: "ma-2103", facility: "USYC Reserve Facility", status: "pending", desc: "Liquidation auction in progress", reserve: 406640, proceeds: 0, variance: 0, txHash: "0x2103232b…2ee3", date: "2026-03-23T20:30:00Z" },
  { id: "tx-0cf2", kind: "Facility Pause", target: "cf-horizon", facility: "Horizon Yield Facility", status: "settled", desc: "Facility temporarily paused", note: "State: paused", txHash: "0x0cf2232e…2ee6", date: "2026-03-23T08:30:00Z" },
  { id: "tx-0cf4", kind: "Facility Shutdown", target: "cf-zenith", facility: "Zenith Multi Facility", status: "settled", desc: "Facility moved to shutdown state", note: "State: shutdown", txHash: "0x0cf4232f…2ee7", date: "2026-03-23T02:30:00Z" },
  { id: "tx-1015", kind: "Account Freeze", target: "ma-1015", facility: "US Treasury Core Facility", status: "settled", desc: "Account frozen due to compliance risk controls", note: "Health factor: 0.00", txHash: "0x10152330…2ee8", date: "2026-03-22T20:30:00Z" },
  { id: "tx-1018", kind: "Account Pause", target: "ma-1018", facility: "US Treasury Core Facility", status: "settled", desc: "Account paused pending operational review", note: "Health factor: 0.00", txHash: "0x10182331…2ee9", date: "2026-03-22T14:30:00Z" },
  { id: "tx-1035", kind: "Account Freeze", target: "ma-1035", facility: "OUSG Stable Income", status: "settled", desc: "Account frozen due to compliance risk controls", note: "Health factor: 0.00", txHash: "0x10352332…2eea", date: "2026-03-22T08:30:00Z" },
  { id: "tx-1038", kind: "Account Pause", target: "ma-1038", facility: "OUSG Stable Income", status: "settled", desc: "Account paused pending operational review", note: "Health factor: 0.00", txHash: "0x10382333…2eeb", date: "2026-03-22T02:30:00Z" },
  { id: "tx-2046", kind: "Auction Resolution", target: "ma-1005", facility: "US Treasury Core Facility", status: "settled", desc: "Liquidation auction settled", reserve: 240010, proceeds: 255452, variance: 15442, txHash: "0x20462334…2eec", date: "2026-03-21T18:30:00Z" },
  { id: "tx-1040", kind: "Account Freeze", target: "ma-1040", facility: "OUSG Stable Income", status: "settled", desc: "Account frozen due to compliance risk controls", note: "Health factor: 0.51", txHash: "0x10402335…2eed", date: "2026-03-21T10:30:00Z" },
];

// ── Shared module stack template ─────────────────────────────────────────
const FACILITY_MODULES = [
  { name: "Dutch Auction v2", type: "Auction", addr: "0xAuc1...Dutch", desc: "Descending price auction with automatic settlement" },
  { name: "Standard Institutional Compliance", type: "Compliance", addr: "0xCmp1...Std", desc: "Modular compliance bundling tx-frequency, borrow-size, and US-jurisdiction rules" },
  { name: "Tiered Fee v2", type: "Fee", addr: "0xFee1...Tiered", desc: "Volume-based tiered fee structure with management and performance fees" },
  { name: "Chainlink Core", type: "Oracle", addr: "0xOra1...CLink", desc: "Chainlink decentralized oracle network for price feeds" },
  { name: "Standard Risk v2", type: "Risk", addr: "0xRisk1...Std", desc: "Default risk engine with LTV-based health factor calculations" },
  { name: "NAV Calculator v1", type: "Valuation", addr: "0xVal1...NAV", desc: "Net asset value calculator for fund-based collateral" },
];

// 7-day utilization sample, deterministic offsets around the facility's current
// rate (no RNG so re-renders stay stable).
const _UTIL_OFFSETS = [-6, 1, -3, 4, 9, -1, 2];

// Build the full detail object for a facility from live account rows.
const buildFacilityDetail = (facility) => {
  const accts = (window.ADMIN_ACCOUNTS || []).filter((a) => a.facility === facility.name);
  const totalCollateral = accts.reduce((s, a) => s + a.collateral, 0);
  const totalBorrowed = accts.reduce((s, a) => s + a.borrowed, 0);

  // Collateral breakdown by token ticker (collToken looks like "248,000 BUIDL").
  const byToken = {};
  accts.forEach((a) => {
    const ticker = String(a.collToken || "").trim().split(/\s+/).pop() || "—";
    byToken[ticker] = (byToken[ticker] || 0) + a.collateral;
  });
  const collateralBreakdown = Object.keys(byToken)
    .map((t) => ({ token: t, value: byToken[t], pct: totalCollateral ? (byToken[t] / totalCollateral) * 100 : 0 }))
    .sort((x, y) => y.value - x.value);

  const statusCount = (s) => accts.filter((a) => a.status === s).length;
  const accountsByStatus = [
    { label: "Active", count: statusCount("active"), color: "var(--success)" },
    { label: "Warn", count: statusCount("warn"), color: "var(--gold-60)" },
    { label: "Default", count: statusCount("default"), color: "var(--danger)" },
  ];

  const cur = facility.utilization;
  const utilization7d = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d, i) => ({
    day: d, value: Math.max(0, Math.min(100, +(cur + _UTIL_OFFSETS[i]).toFixed(1))),
  }));

  const collateralTokens = collateralBreakdown.map((c) => c.token).filter((t) => t !== "—");
  const settlementTokens = facility.token === "USDC" ? ["USDC", "USDT"] : [facility.token];

  return {
    config: {
      collateralTokens: collateralTokens.length ? collateralTokens : ["—"],
      settlementTokens,
      interestRate: facility.rate,
      liqThreshold: 150,
      maxLTV: 67,
      poolTVL: facility.tvl,
      utilization: facility.utilization,
      totalBorrowed: totalBorrowed,
    },
    kpis: {
      totalCollateral, totalBorrowed,
      utilization: facility.utilization,
      activeAccounts: accts.length,
      warn: statusCount("warn"), default: statusCount("default"),
    },
    charts: { collateralBreakdown, utilization7d, accountsByStatus },
    accounts: accts,
    policy: FACILITY_POLICY,
    roles: FACILITY_ROLES,
    modules: FACILITY_MODULES,
    ddf: {
      reserve: { total: 0, committed: 0, available: 0, utilization: 0 },
      activeAuctions: [
        { id: "DDF-2046", account: "ma-1005", bid: 240010, reserve: 255452, bids: 6, time: "1h 55m", status: "ending soon" },
        { id: "DDF-2048", account: "ma-1015", bid: 520259, reserve: 579051, bids: 3, time: "7h 8m", status: "active" },
        { id: "DDF-2050", account: "ma-1020", bid: 650317, reserve: 676953, bids: 7, time: "10h 21m", status: "ending soon" },
      ],
      resolutionRecords: [
        { auction: "DDF-2041", account: "ma-5073", auctionStatus: "settled", reserveAdvance: 102510, proceeds: 169840, variance: 67330, finalStatus: "closed" },
        { auction: "DDF-2039", account: "ma-1100", auctionStatus: "settled", reserveAdvance: 74800, proceeds: 75600, variance: 800, finalStatus: "closed" },
        { auction: "DDF-2037", account: "ma-1160", auctionStatus: "settled", reserveAdvance: 87550, proceeds: 96560, variance: 9010, finalStatus: "closed" },
      ],
      reconciliation: { expectedReplenishment: 264860, actualProceeds: 342000, variance: 77140 },
    },
    // Facility-scoped at-risk queue (from the global liquidation monitor).
    liquidationQueue: (window.ADMIN_LIQUIDATIONS || []).filter((p) => p.facility === facility.name),
  };
};

// ── F2: deploy-wizard option lists ───────────────────────────────────────
const DEPLOY_WIZARD_OPTIONS = {
  risk: [
    { name: "Aggressive Growth", desc: "Higher-risk tolerance model for growth-oriented facilities", params: [["Max LTV", "85%"], ["Liquidation threshold", "90%"], ["Haircut", "5%"], ["Health-factor floor", "1.05"]] },
    { name: "Institutional Guardrail", desc: "Conservative model for regulated institutional capital", params: [["Max LTV", "60%"], ["Liquidation threshold", "70%"], ["Haircut", "12%"], ["Health-factor floor", "1.25"]] },
    { name: "Standard Risk v2", desc: "Default LTV-based health-factor engine", params: [["Max LTV", "67%"], ["Liquidation threshold", "80%"], ["Haircut", "8%"], ["Health-factor floor", "1.10"]] },
  ],
  auction: [
    { name: "Batch Clearing", desc: "Batch order matching with uniform clearing price", params: [["Style", "Batch / uniform clearing"], ["Bidding window", "4 hours"], ["Min participation", "3 bidders"]] },
    { name: "Dutch Auction v2", desc: "Descending price auction with automatic settlement", params: [["Style", "Descending price"], ["Bidding window", "2 hours"], ["Min participation", "1 bidder"]] },
    { name: "Sealed Bid", desc: "Sealed first-price bids revealed at close", params: [["Style", "Sealed first-price"], ["Bidding window", "6 hours"], ["Min participation", "2 bidders"]] },
  ],
  valuation: [
    { name: "None", desc: "No valuation module", params: [] },
    { name: "NAV Calculator v1", desc: "Net asset value calculator for fund-based collateral", params: [["Refresh", "Daily"], ["Source", "Administrator NAV feed"]] },
  ],
  liquidity: [
    { name: "None", desc: "No liquidity module", params: [] },
    { name: "AMM Pool Router", desc: "Routes idle liquidity through an AMM pool", params: [["Router", "Uniswap v3"], ["Slippage cap", "0.5%"]] },
  ],
  fee: [
    { name: "Flat Fee v1", desc: "Simple flat-rate fee applied uniformly across all transactions", params: [["Origination fee", "0.50%"], ["Servicing fee", "0.25% APR"], ["Liquidation fee", "5.00%"]] },
    { name: "RWA Split Fee", desc: "Split fee structure for real-world-asset facilities", params: [["Origination fee", "0.75%"], ["Servicing fee", "0.40% APR"], ["Liquidation fee", "4.00%"]] },
    { name: "Tiered Fee v2", desc: "Volume-based tiered fee structure", params: [["Origination fee", "0.30%"], ["Servicing fee", "0.20% APR"], ["Liquidation fee", "5.00%"]] },
  ],
  compliance: [
    { name: "Standard Institutional Compliance", desc: "Modular compliance bundling tx-frequency, borrow-size, and US-jurisdiction rules", params: [["Max transactions", "5 / 7 days"], ["Borrow size", "$10,000 to $5,000,000"], ["Jurisdiction TVL cap", "US ≤ 40% of TVL"], ["Min credit score", "650"]] },
    { name: "Aggressive RWA Compliance", desc: "Loosened caps and longer trading windows for high-velocity RWA facilities", params: [["Max transactions", "15 / 7 days"], ["Borrow size", "$25,000 to $25,000,000"], ["Jurisdiction TVL cap", "No cap"], ["Min credit score", "600"]] },
    { name: "EU Qualified Compliance", desc: "MiCA-aligned gating for EU-qualified investors", params: [["Max transactions", "8 / 7 days"], ["Borrow size", "€20,000 to €10,000,000"], ["Jurisdiction TVL cap", "EU ≤ 60% of TVL"], ["Min credit score", "680"]] },
  ],
  registries: [
    { label: "Ascend Default Registry (shared with 4 facilities)", jurisdiction: "US", issuer: "Ascend · 0xA5cE…ABcD", policy: "Standard institutional gating: KYC + accreditation." },
    { label: "Ascend EU Qualified Registry (shared with 1 facility)", jurisdiction: "EU", issuer: "Ascend · 0xA5cE…ABcD", policy: "MiCA-aligned gating for EU-qualified investors." },
    { label: "Ascend Institutional-Only Registry (shared with 0 facilities)", jurisdiction: "US", issuer: "Ascend · 0xA5cE…ABcD", policy: "Accredited / qualified institutional buyers only." },
    { label: "Create new registry dedicated to this facility", jurisdiction: "—", issuer: "—", policy: "Define a fresh claim policy for this facility." },
  ],
  collateralTokens: ["BUIDL", "OUSG", "USYC", "BENJI", "STBT"],
  settlement: { USD: ["USDC", "USDT", "USD1"], EUR: ["EURC"] },
  claimTopics: ["KYC verified", "Accredited Investor", "Partner Membership", "Corporate Email Verified"],
};

// ── F3: per-account detail, derived from the account row + its facility ──
// Accepts a full account row or a liquidation position (looks the full row up
// by id and merges; falls back to the passed object for positions not in the
// account set). borrowed falls back to a position's debt field.
const buildAccountDetail = (acct) => {
  const base = (window.ADMIN_ACCOUNTS || []).find((a) => a.id === acct.id) || acct;
  const facility = (window.ADMIN_FACILITIES || []).find((f) => f.name === base.facility) || {};
  const collateral = base.collateral || 0;
  const borrowed = base.borrowed != null ? base.borrowed : (base.debt || 0);
  const rate = facility.rate || 5.0;
  const dailyAccrual = borrowed * (rate / 100) / 365;
  const interestAccrued = Math.round(dailyAccrual * 15);
  const totalOwed = borrowed + interestAccrued;
  const ltv = collateral ? (borrowed / collateral) * 100 : 0;
  const parts = String(base.collToken || "").trim().split(/\s+/);
  const ticker = parts.length > 1 ? parts[parts.length - 1] : (parts[0] || "—");
  const qty = parts.length > 1 ? parts.slice(0, -1).join(" ") : "—";
  return {
    id: base.id,
    wallet: base.wallet || acct.wallet || "—",
    facility: base.facility,
    settlement: facility.token || "USDC",
    status: base.status || acct.status || "default",
    hf: base.hf != null ? base.hf : (acct.hf || 0),
    ddfEnabled: true,
    ltv, maxLTV: 91, liqThreshold: 110,
    collateral, borrowed, available: base.available || 0,
    interestAccrued, interestRate: rate, dailyAccrual, totalOwed,
    collateralRows: [{ token: ticker, amount: qty, value: collateral, pct: 100 }],
    lastPayment: "2026-03-13", nextPayment: "2026-04-11",
  };
};

// ── F5: per-pool detail (lender positions, IOUs, mint/burn events) ───────
const _POOL_LENDERS = [
  { wallet: "0x1b75…f94e", name: "Default Searcher" },
  { wallet: "0x90F8…c9C1", name: "Bob Smith" },
  { wallet: "0x3a2b…9a0b", name: "Sarah Connor" },
  { wallet: "0x6666…5555", name: "Vista Capital" },
  { wallet: "0x2222…1111", name: "North Harbor LLC" },
  { wallet: "0x7777…2222", name: "Helix Partners" },
];

const buildPoolDetail = (pool) => {
  const n = Math.max(1, pool.lenders || 1);
  // Decreasing weights so the largest lender leads; deposits sum to pool TVL.
  const weights = Array.from({ length: n }, (_, i) => n - i);
  const wsum = weights.reduce((s, w) => s + w, 0);
  const positions = weights.map((w, i) => {
    const deposited = Math.round((pool.tvl * w) / wsum);
    const share = (w / wsum) * 100;
    const yieldEarned = Math.round(deposited * (pool.apy / 100) * 0.12);
    const L = _POOL_LENDERS[i % _POOL_LENDERS.length];
    return {
      wallet: L.wallet, name: L.name, deposited, share,
      lpTokens: deposited, yieldEarned, withdrawable: deposited + yieldEarned,
    };
  });
  const totalDeposited = positions.reduce((s, p) => s + p.deposited, 0);
  const totalYield = positions.reduce((s, p) => s + p.yieldEarned, 0);
  const iouOriginal = Math.round(pool.tvl * 0.08);
  const iouRepaid = Math.round(iouOriginal * 0.15);
  return {
    name: `${pool.token} lending pool`,
    facility: pool.facility, tvl: pool.tvl, apy: pool.apy, utilization: pool.utilization, lenders: n,
    totalDeposited, totalYield, positions,
    iou: { id: `iou-${pool.id}`, status: "partially repaid", original: iouOriginal, repaid: iouRepaid, remaining: iouOriginal - iouRepaid },
    events: [
      { type: "BURN", amount: iouRepaid, date: "2026-03-20" },
      { type: "MINT", amount: iouOriginal, date: "2026-03-15" },
    ],
  };
};

// ── F8: audit-report datasets + a shared CSV download util (reused by F9) ─
const ADMIN_REPORT_ROWS = {
  "Compliance Actions": [
    { date: "2026-05-21", actor: "admin-1", target: "user-4",    action: "Freeze",   details: "Suspicious transaction pattern flagged", status: "executed" },
    { date: "2026-05-20", actor: "admin-1", target: "user-2",    action: "Clawback", details: "500 USDC clawback - regulatory requirement", status: "executed" },
    { date: "2026-05-15", actor: "admin-1", target: "cf-horizon", action: "Pause",    details: "High volatility in underlying asset", status: "executed" },
    { date: "2026-05-10", actor: "admin-2", target: "user-3",    action: "Encumber", details: "1,000 BENJI encumbered - pending investigation", status: "pending" },
    { date: "2026-05-05", actor: "admin-2", target: "cf-fmm",     action: "Unpause",  details: "Maintenance window completed", status: "executed" },
  ],
  "Investor Activity": [
    { date: "2026-05-22", actor: "0x1b75…f94e", target: "US Treasury core facility", action: "Deposit",  details: "Deposited 250,000 BUIDL collateral", status: "executed" },
    { date: "2026-05-21", actor: "0x90F8…c9C1", target: "BUIDL yield facility",      action: "Borrow",   details: "Drew down 120,000 USDC", status: "executed" },
    { date: "2026-05-19", actor: "0x3a2b…9a0b", target: "OUSG stable income",        action: "Repay",    details: "Repaid 60,000 USDC principal", status: "executed" },
    { date: "2026-05-17", actor: "0x6666…5555", target: "US Treasury core facility", action: "Withdraw", details: "Withdrew 40,000 BUIDL collateral", status: "executed" },
  ],
  "KYC Submissions": [
    { date: "2026-05-22", actor: "Sumsub",  target: "Vista Capital", action: "Submitted", details: "Qualified premium attestation", status: "pending" },
    { date: "2026-05-20", actor: "Onfido",  target: "Aline Winters", action: "Approved",  details: "KYC verified, CH jurisdiction", status: "executed" },
    { date: "2026-05-18", actor: "Onfido",  target: "Bob Smith",     action: "Rejected",  details: "Document mismatch", status: "executed" },
  ],
  "Liquidation Events": [
    { date: "2026-05-21", actor: "DDF searcher", target: "ma-5073", action: "Auction settled",   details: "Proceeds 169,840 USDC, variance +67,330", status: "executed" },
    { date: "2026-05-20", actor: "DDF searcher", target: "ma-1100", action: "Auction settled",   details: "Proceeds 75,600 USDC, variance +800", status: "executed" },
    { date: "2026-05-19", actor: "DDF searcher", target: "ma-2103", action: "Auction triggered", details: "Reserve advance 406,640 USDC", status: "pending" },
  ],
  "Identity Changes": [
    { date: "2026-05-22", actor: "Ascend", target: "0x6666…5555", action: "Claim added",      details: "Accredited Investor claim attached to ONCHAINID", status: "executed" },
    { date: "2026-05-19", actor: "Ascend", target: "0x9c2d…77b8", action: "ONCHAINID created", details: "New ONCHAINID minted for investor", status: "executed" },
    { date: "2026-05-16", actor: "Ascend", target: "0x3a2b…9a0b", action: "Claim revoked",    details: "KYC claim withdrawn pending recertification", status: "executed" },
  ],
  "Facility Operations": [
    { date: "2026-05-22", actor: "admin@ascend.io", target: "cf-usdc-core", action: "Config change", details: "Interest rate updated to 5.5%", status: "executed" },
    { date: "2026-05-20", actor: "admin@ascend.io", target: "cf-prime-inst", action: "Deploy",        details: "Facility deployed with Standard Institutional Compliance", status: "executed" },
    { date: "2026-05-10", actor: "ops@ascend.io",   target: "cf-zenith",     action: "Shutdown",      details: "Facility moved to shutdown state", status: "executed" },
  ],
};

// Build a CSV string and trigger a client-side download (reused by F8 + F9).
const downloadCSV = (filename, headers, rows) => {
  const esc = (v) => {
    const s = String(v == null ? "" : v);
    return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  };
  const csv = [headers.map(esc).join(","), ...rows.map((r) => r.map(esc).join(","))].join("\n");
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 100);
};

Object.assign(window, {
  buildFacilityDetail, buildAccountDetail, buildPoolDetail, FACILITY_POLICY,
  FACILITY_ROLES, FACILITY_MODULES, DEPLOY_WIZARD_OPTIONS, ADMIN_MODULE_WHITELIST,
  ADMIN_TRANSACTIONS, ADMIN_REPORT_ROWS, downloadCSV,
});
