// AdminMarginAccounts.jsx — global margin-account table with operational
// controls. The OZ version showed "0.00" in red for frozen/paused accounts,
// which is misleading: those accounts aren't at liquidation risk — borrowing
// is simply disabled. Renée C-6 fix: a frozen/paused/liquidated account shows
// "—" with a context line, and red HF is reserved for genuine default risk.

const HF_DISABLED = new Set(["frozen", "paused", "liquidated"]);

const HFCell = ({ account }) => {
  if (HF_DISABLED.has(account.status)) {
    const why = account.status === "liquidated" ? "Position closed" : "Borrowing disabled";
    return (
      <div style={{ textAlign: "right" }} title={`Health factor not applicable — ${why.toLowerCase()} while ${account.status}`}>
        <div style={{ font: '500 14px/18px "Inter", sans-serif', color: "var(--fg-faint)" }}>—</div>
        <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{why}</div>
      </div>
    );
  }
  const v = account.hf;
  const color = v < 1.0 ? "var(--danger)" : v < 1.2 ? "var(--danger)" : v < 1.5 ? "var(--gold-70)" : "var(--success)";
  const label = v < 1.0 ? "In default" : v < 1.5 ? "At risk" : "Healthy";
  return (
    <div style={{ textAlign: "right" }}>
      <div className="tnum" style={{ font: '600 15px/18px "Inter", sans-serif', color }}>{v.toFixed(2)}</div>
      <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{label}</div>
    </div>
  );
};

const AccountActions = ({ account, onAction }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const items = [];
  if (account.status === "frozen") items.push({ key: "unfreeze-account", label: "Unfreeze account", icon: "play" });
  else items.push({ key: "freeze-account", label: "Freeze account", icon: "snowflake", tone: "danger" });
  if (account.status === "paused") items.push({ key: "unpause-account", label: "Unpause account", icon: "play" });
  else if (account.status !== "frozen" && account.status !== "liquidated") items.push({ key: "pause-account", label: "Pause account", icon: "pause" });
  items.push({ key: "view", label: "View on explorer", icon: "external" });

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button className="btn btn--secondary btn--sm" type="button" onClick={(e) => { e.stopPropagation(); setOpen(!open); }}>
        Actions <Icon name="chevDown" size={12} stroke={1.6}/>
      </button>
      {open && (
        <div style={{ position: "absolute", right: 0, top: "calc(100% + 4px)", zIndex: 20, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 8, boxShadow: "var(--shadow-1)", minWidth: 190, padding: 4 }}>
          {items.map((it) => (
            <button key={it.key} type="button" onClick={() => { setOpen(false); onAction(it.key, account); }}
              style={{ all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", borderRadius: 6, width: "100%", boxSizing: "border-box", font: '500 13px/18px "Inter", sans-serif', color: it.tone === "danger" ? "var(--danger)" : "var(--fg)" }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <Icon name={it.icon} size={13} stroke={1.6}/> {it.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const AdminMarginAccounts = ({ accounts, totals, onAction, 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 margin accounts" onRetry={onRetry} />;

  const counts = {
    all: accounts.length,
    active: accounts.filter(a => a.status === "active").length,
    warn: accounts.filter(a => a.status === "warn").length,
    default: accounts.filter(a => a.status === "default").length,
    paused: accounts.filter(a => a.status === "paused").length,
    frozen: accounts.filter(a => a.status === "frozen").length,
    liquidated: accounts.filter(a => a.status === "liquidated").length,
  };
  const filtered = accounts.filter(a =>
    (filter === "all" || a.status === filter) &&
    (q === "" || a.id.includes(q) || a.facility.toLowerCase().includes(q.toLowerCase()) || a.wallet.includes(q))
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Credit facilities" title="Margin accounts" icon="accounts"
        lede="Global view of every margin account across credit facilities, with operational controls."
        annot="C-5 sentence case" />

      <HeroStrip
        hero={{ label: "Total collateral posted", value: fmtMoneyShort(totals.collateral), sub: `Across ${totals.total} accounts · ${fmtMoneyShort(totals.borrowed)} borrowed` }}
        supports={[
          { label: "Accounts", value: totals.total, sub: `${totals.active} active · ${totals.warn} warn` },
          { label: "Avg health factor", value: totals.avgHF.toFixed(2), sub: "Active accounts only", tone: totals.avgHF < 1.5 ? "warning" : undefined },
          { label: "Needs attention", value: totals.default + totals.frozen, sub: `${totals.default} default · ${totals.frozen} frozen · ${totals.liquidated} liquidated`, tone: "danger" },
        ]}
      />

      <div>
        <SectionHeader eyebrow="Accounts" title="All margin accounts" count={filtered.length}
          annot="C-6 health-factor context · C-2 ma-id + facility"
          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: "active", label: "Active", count: counts.active },
            { value: "warn", label: "Warn", count: counts.warn },
            { value: "default", label: "Default", count: counts.default },
            { value: "paused", label: "Paused", count: counts.paused },
            { value: "frozen", label: "Frozen", count: counts.frozen },
            { value: "liquidated", label: "Liquidated", count: counts.liquidated },
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "120px 150px 1.4fr 1fr 1fr 1fr 110px 110px 110px", gap: 14, padding: "10px 20px", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Account</Th><Th>Wallet</Th><Th>Linked facility</Th>
              <Th align="right" sortable>Collateral</Th><Th align="right" sortable>Borrowed</Th><Th align="right">Available</Th>
              <Th align="right" sortable>Health</Th><Th>Status</Th><Th align="right">Actions</Th>
            </div>
            {filtered.length === 0 ? (
              <EmptyState icon="search" title="No accounts match" body="Adjust the filter or search to see other accounts." secondary={{ label: "Show all", onClick: () => { setFilter("all"); setQ(""); } }} />
            ) : filtered.map((a, i) => (
              <div key={a.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "120px 150px 1.4fr 1fr 1fr 1fr 110px 110px 110px", gap: 14, padding: "14px 20px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                <div style={{ minWidth: 0 }}>
                  <span className="addr" style={{ font: '500 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{a.id}</span>
                  {a.adminLastActor && (
                    <div style={{ display: "flex", alignItems: "center", gap: 4, marginTop: 3 }}>
                      <Icon name="docs" size={10} stroke={1.6} style={{ color: "var(--fg-faint)", flexShrink: 0 }} />
                      <span style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {a.adminLastAction} · <span title={fmtDateTime(a.adminLastAt)}>{fmtRelative(a.adminLastAt)}</span>
                      </span>
                    </div>
                  )}
                </div>
                <MonoAddr full={a.wallet} />
                <button onClick={() => onNavigate && onNavigate("facilities")} style={{ all: "unset", cursor: "pointer", minWidth: 0 }}>
                  <div style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--accent)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.facility}</div>
                  <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{a.collToken}</div>
                </button>
                <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.collateral)}</span>
                <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(a.borrowed)}</span>
                <span className="tnum" style={{ textAlign: "right", font: '500 14px "Inter", sans-serif', color: a.available > 0 ? "var(--fg)" : "var(--fg-faint)" }}>{fmtMoney(a.available)}</span>
                <HFCell account={a} />
                <div><AdminStatus status={a.status} /></div>
                <div style={{ display: "flex", justifyContent: "flex-end" }}><AccountActions account={a} onAction={onAction} /></div>
              </div>
            ))}
          </div>
        </section>
        <div style={{ marginTop: 12, font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
          Showing {filtered.length} of {totals.total} accounts · this prototype renders a representative slice.
        </div>
      </div>
    </div>
  );
};

window.AdminMarginAccounts = AdminMarginAccounts;
