// MarginAccountsPage.jsx — Account-level list across every facility.
// Destination of "View all" on the Portfolio facilities table and the
// Facility Detail margin-accounts section.
//
// Renée lens:
//   · C-2: each row is ma-id + a distinguishable facility name, never a wall
//     of identical labels.
//   · C-4: hero "Margin equity" carries weight; supporting KPIs sit in a
//     hairline strip; account rows are label/value cards, not equal-weight
//     stat tiles.
//   · C-6: the min-health-factor "0.00" gets a plain-English context line —
//     this is the exact OZ bug Renée flagged ("Min Health Factor 0.00 in red
//     with zero context"). Here the red number always carries its reason.
//
// Component name is MarginAccountsPage to avoid colliding with the
// MarginAccounts section component in FacilityScreen.jsx.

const AccountCard = ({ account, onAction, onOpenFacility }) => {
  const v = parseFloat(account.hf);
  const liquidated = account.status === "default";
  const atRisk = account.status === "at-risk";
  const hfColor = liquidated || v < 1.2 ? "var(--danger)" :
                  atRisk || v < 1.5    ? "var(--gold-70)" :
                                          "var(--success)";
  const hfLabel = liquidated ? "Liquidated" :
                  v < 1.2    ? "Liquidation risk" :
                  v < 1.5    ? "At risk" : "Healthy";
  // The at-risk variant gets the gold left-border accent (prompt 4.8);
  // liquidated gets the danger accent.
  const accent = atRisk ? "var(--gold-60)" : liquidated ? "var(--danger)" : "transparent";

  return (
    <div className="acct-card" style={{
      background: "var(--surface)",
      border: "1px solid var(--border)",
      borderLeft: `3px solid ${accent}`,
      borderRadius: 12,
      padding: 20,
      display: "flex", flexDirection: "column", gap: 16,
    }}>
      {/* Header */}
      <div className="acct-head" style={{
        display: "grid", gridTemplateColumns: "auto 1fr auto",
        gap: 14, alignItems: "center",
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: "var(--bg-alt)", color: "var(--fg-muted)",
          display: "grid", placeItems: "center", flexShrink: 0,
        }}>
          <Icon name="accounts" size={18} stroke={1.5}/>
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 2 }}>
            <span className="addr" style={{
              font: '600 15px/20px "JetBrains Mono", monospace', color: "var(--fg)",
            }}>{account.id}</span>
            <StatusPill variant={liquidated ? "frozen" : account.status}>{account.statusLabel}</StatusPill>
          </div>
          <button onClick={() => onOpenFacility && onOpenFacility({ id: account.facilityId, name: account.facility })}
                  style={{
            all: "unset", cursor: "pointer",
            font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)",
            display: "inline-flex", alignItems: "center", gap: 5,
          }}
          onMouseEnter={(e) => e.currentTarget.style.color = "var(--accent)"}
          onMouseLeave={(e) => e.currentTarget.style.color = "var(--fg-subtle)"}>
            <Icon name="facility" size={12} stroke={1.5}/>
            {account.facility}
          </button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
          <div className="tnum" style={{
            font: '600 24px/28px "Inter", sans-serif', color: hfColor,
            letterSpacing: "-0.012em",
          }}>{v.toFixed(2)}</div>
          <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Health · {hfLabel}
          </div>
        </div>
      </div>

      {/* Liquidated / at-risk context line — never a naked status (C-6) */}
      {(atRisk || liquidated) && (
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "8px 12px", borderRadius: 8,
          background: liquidated ? "var(--red-10)" : "var(--gold-10)",
          color: liquidated ? "var(--red-80)" : "var(--gold-80)",
          font: '400 12px/16px "Inter", sans-serif',
        }}>
          <Icon name={liquidated ? "alert" : "info"} size={13} stroke={1.7}/>
          {liquidated
            ? "Position was liquidated. Collateral was sold to cover the borrow; remaining equity is withdrawable."
            : "Health factor is approaching the liquidation threshold. Add collateral or repay to improve it."}
        </div>
      )}

      {/* Stats */}
      <div className="acct-stats" style={{
        display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16,
        paddingTop: 16, borderTop: "1px solid var(--border)",
      }}>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Collateral</div>
          <div className="tnum" style={{ font: '600 17px/22px "Inter", sans-serif', color: "var(--fg)", marginTop: 2 }}>{account.collateral}</div>
        </div>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Borrowed</div>
          <div className="tnum" style={{ font: '600 17px/22px "Inter", sans-serif', color: "var(--fg)", marginTop: 2 }}>{account.borrowed}</div>
        </div>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Available to borrow</div>
          <div className="tnum" style={{ font: '600 17px/22px "Inter", sans-serif', color: "var(--accent)", marginTop: 2 }}>{account.available}</div>
        </div>
        <div>
          <div className="stat-label" style={{ fontSize: 11 }}>Current LTV</div>
          <div className="tnum" style={{ font: '600 17px/22px "Inter", sans-serif', color: "var(--fg)", marginTop: 2 }}>{account.ltv}</div>
        </div>
      </div>

      {/* Actions */}
      <div className="acct-actions" style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 8, flexWrap: "wrap",
      }}>
        <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
          Opened {account.opened} · Last action {account.lastAction}
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {liquidated ? (
            <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("withdraw", account)}>
              <Icon name="withdraw" size={12} stroke={1.6}/> Withdraw equity
            </button>
          ) : (
            <>
              <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("deposit", account)}>
                <Icon name="deposit" size={12} stroke={1.6}/> Deposit
              </button>
              <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("withdraw", account)}>
                <Icon name="withdraw" size={12} stroke={1.6}/> Withdraw
              </button>
              <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("borrow", account)}>Borrow</button>
              <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("repay", account)}>Repay</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

const MarginAccountsPage = ({ data, onAction, onOpenFacility, state = "live", onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load your margin accounts" body="Account data is fetched per-wallet; this might be a wallet-connection blip." onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
        <div>
          <Eyebrow>Borrow</Eyebrow>
          <h1 style={{ margin: "6px 0 6px", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Margin accounts</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Every margin account you hold, across all facilities.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="accounts"
            title="No margin accounts yet"
            body="Open a margin account inside a credit facility to deposit collateral and borrow. You can open more than one to keep risk profiles separate."
            action={{ label: "Browse facilities", icon: "facility", onClick: () => onOpenFacility && onOpenFacility(null) }}
          />
        </section>
      </div>
    );
  }

  const filtered = data.accounts.filter((a) =>
    filter === "all"     ? true :
    filter === "healthy" ? a.status === "healthy" :
    filter === "at-risk" ? a.status === "at-risk" :
    filter === "default" ? a.status === "default" : true
  );

  const k = data.kpi;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      {/* Header */}
      <div data-annot-note="C-5 sentence case">
        <Eyebrow>Borrow</Eyebrow>
        <h1 style={{
          margin: "6px 0 6px",
          font: '700 32px/36px "Figtree", sans-serif',
          letterSpacing: "-0.015em", color: "var(--fg)",
        }}>Margin accounts</h1>
        <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 640 }}>
          Every margin account you hold, across all facilities. Each isolates
          its own collateral and borrow position.
        </div>
      </div>

      {/* Hero KPI + supporting strip */}
      <section style={{ display: "flex", gap: 16, flexWrap: "wrap" }} data-annot-note="C-4 hierarchy">
        <HeroKPI
          label="Margin equity"
          value={k.equity}
          sub={k.equitySub}
        />
        <div className="kpi-strip" style={{
          flex: "3 1 480px", minWidth: 0,
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 12, display: "flex", flexWrap: "wrap",
        }}>
          <SupportKPI label="Total collateral" value={k.totalCollateral} sub="Posted across accounts" />
          <SupportKPI label="Total borrowed"   value={k.totalBorrowed}   sub="Drawn against collateral" />
          <SupportKPI label="Accounts"         value={k.accounts}        sub={k.accountsSub} />
          {/* C-6: min HF carries its reason; never a naked red number */}
          <SupportKPI label="Min health factor" value={k.minHF} sub={k.minHFSub} tone="danger" last />
        </div>
      </section>

      {/* Filter */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <SegmentControl
          value={filter}
          onChange={setFilter}
          options={[
            { value: "all",     label: "All",        count: data.accounts.length },
            { value: "healthy", label: "Healthy",    count: data.accounts.filter(a => a.status === "healthy").length },
            { value: "at-risk", label: "At risk",    count: data.accounts.filter(a => a.status === "at-risk").length },
            { value: "default", label: "Liquidated", count: data.accounts.filter(a => a.status === "default").length },
          ]}
        />
        <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("create")}>
          <Icon name="plus" size={12} stroke={1.8}/> New account
        </button>
      </div>

      {/* Account cards */}
      <section data-annot-note="C-2 distinguishable labels · C-6 health context" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {filtered.length === 0 ? (
          <section className="card" style={{ padding: 0 }}>
            <EmptyState
              icon="search"
              title="No accounts in this bucket"
              body="Adjust the filter above to see accounts in another health state."
              secondary={{ label: "Show all", onClick: () => setFilter("all") }}
            />
          </section>
        ) : (
          filtered.map((a) => (
            <AccountCard key={a.id} account={a} onAction={onAction} onOpenFacility={onOpenFacility} />
          ))
        )}
      </section>
    </div>
  );
};

Object.assign(window, { MarginAccountsPage, AccountCard });
