// AdminMarginAccountDetail.jsx — F3. Per-account detail: HF gauge, KPI row,
// collateral breakdown, debt summary, account info, and admin actions. Reached
// from the accounts table and the liquidation monitor. Actions route through
// ConfirmAction (Freeze/Unfreeze, Pause/Unpause); Clawback and Migrate/Recover
// are F11 (P3). Resolves the live account from the App's accounts state so a
// ConfirmAction mutation reflects here.

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

const HFGauge = ({ hf, status }) => {
  if (MAD_HF_DISABLED.has(status)) {
    return (
      <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
        Health factor not applicable while {status}. {status === "liquidated" ? "Position closed." : "Borrowing disabled."}
      </div>
    );
  }
  const pct = Math.max(3, Math.min(100, (hf / 2) * 100));
  const tone = hf < 1.0 ? "var(--danger)" : hf < 1.5 ? "var(--gold-70)" : "var(--success)";
  const note = hf < 1.0
    ? "Health factor is below 1.0. Account is liquidatable."
    : hf < 1.5
      ? "Health factor is below 1.5. This account is at risk of liquidation."
      : "Healthy. Comfortably above the liquidation threshold.";
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
        <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Current</span>
        <span className="tnum" style={{ font: '700 28px/32px "Figtree", sans-serif', color: tone, letterSpacing: "-0.01em" }}>{hf.toFixed(2)}</span>
      </div>
      <div style={{ position: "relative", height: 8, borderRadius: "var(--radius-sm)", background: "var(--black-10)", margin: "var(--space-12) 0 var(--space-8)", overflow: "hidden" }}>
        <div style={{ width: `${pct}%`, height: "100%", background: tone, borderRadius: "var(--radius-sm)" }} />
        {/* liquidation line at hf=1.0 (50% of the 0..2 scale) */}
        <div style={{ position: "absolute", left: "50%", top: -2, bottom: -2, width: 2, background: "var(--fg-faint)" }} />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", font: '400 11px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
        <span>Liquidation</span><span>Safe</span>
      </div>
      <div style={{ marginTop: "var(--space-12)", padding: "var(--space-12) var(--space-12)", borderRadius: "var(--radius-md)", background: hf < 1.5 ? "var(--gold-10)" : "var(--green-10)", font: '400 12px/18px "Inter", sans-serif', color: hf < 1.5 ? "var(--gold-80)" : "var(--success)" }}>{note}</div>
    </div>
  );
};

const MADCard = ({ title, children, action }) => (
  <section className="card" style={{ padding: 0 }}>
    {title && (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", 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 MADRow = ({ label, value, tone }) => (
  <div style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-12)", padding: "var(--space-8) 0", borderTop: "1px solid var(--border)" }}>
    <span style={{ font: '400 13px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{label}</span>
    <span className="tnum" style={{ font: '500 13px "Inter", sans-serif', color: tone || "var(--fg)", textAlign: "right" }}>{value}</span>
  </div>
);

const AdminMarginAccountDetail = ({ account, accounts, onBack, onAction, state, onRetry }) => {
  if (state === "loading") return <PageSkeleton shape="dashboard" />;
  if (state === "error") return <PageError title="Couldn't load the account" onRetry={onRetry} />;
  if (!account) return <PageError title="No account selected" onRetry={onBack} />;

  // Resolve the live account from App state so ConfirmAction mutations show here.
  const live = (accounts || []).find((a) => a.id === account.id) || account;
  const d = buildAccountDetail(live);

  const hfTone = d.hf === 0 ? "var(--fg-faint)" : d.hf < 1.2 ? "var(--danger)" : d.hf < 1.5 ? "var(--gold-70)" : "var(--success)";
  const hfLabel = MAD_HF_DISABLED.has(d.status) ? "Not applicable" : d.hf < 1.0 ? "In default" : d.hf < 1.5 ? "At risk" : "Healthy";

  // Admin actions (route through ConfirmAction; Clawback/Migrate = F11).
  const payload = { id: d.id, name: d.id, facility: d.facility, collateral: d.collateral, borrowed: d.borrowed };
  const actions = [];
  if (d.status === "frozen") actions.push({ key: "unfreeze-account", label: "Unfreeze account", icon: "play", primary: true });
  else actions.push({ key: "freeze-account", label: "Freeze account", icon: "snowflake", danger: true });
  if (d.status === "paused") actions.push({ key: "unpause-account", label: "Unpause account", icon: "play" });
  else if (d.status !== "frozen" && d.status !== "liquidated") actions.push({ key: "pause-account", label: "Pause account", icon: "pause" });
  actions.push({ key: "clawback-account", label: "Clawback", icon: "clawback", danger: true });
  actions.push({ key: "migrate-recover", label: "Migrate / recover", icon: "refresh" });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-20)" }}>
      {/* Header */}
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-12)" }}>
        <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 margin accounts
        </button>
        <div style={{ display: "flex", alignItems: "center", gap: "var(--space-12)", flexWrap: "wrap" }}>
          <h1 className="addr" style={{ margin: 0, font: '700 24px/30px "JetBrains Mono", monospace', letterSpacing: "-0.01em", color: "var(--fg)" }}>{d.id}</h1>
          <AdminStatus status={d.status} />
          {d.ddfEnabled && <span className="chip chip--info" style={{ padding: "var(--space-2) var(--space-8)", fontSize: 11 }}>DDF enabled</span>}
        </div>
        <div className="addr" style={{ font: '400 13px "JetBrains Mono", monospace', color: "var(--fg-subtle)" }}>{d.wallet} · <span style={{ fontFamily: "Inter" }}>{d.facility}</span></div>
      </div>

      {/* KPI row */}
      <div className="kpi-strip" style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)" }}>
        <SupportKPI label="Health factor" value={MAD_HF_DISABLED.has(d.status) ? "—" : d.hf.toFixed(2)} sub={hfLabel} tone={d.hf < 1.5 && !MAD_HF_DISABLED.has(d.status) ? (d.hf < 1.0 ? "danger" : "warning") : undefined} />
        <SupportKPI label="LTV" value={`${d.ltv.toFixed(0)}%`} sub={`Max ${d.maxLTV}%`} />
        <SupportKPI label="Total owed" value={fmtMoney(d.totalOwed)} sub={`+${fmtMoney(d.dailyAccrual)}/day`} />
        <SupportKPI label="Liq. threshold" value={`${d.liqThreshold}%`} sub="Collateral / debt" />
      </div>

      {/* Body: left detail, right info + actions */}
      <div className="dash-cols" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: "var(--space-16)", alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <MADCard title="Health factor"><HFGauge hf={d.hf} status={d.status} /></MADCard>
          <MADCard title="Collateral breakdown">
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: "0 16px", marginBottom: "var(--space-8)" }}>
              <span style={{ font: '500 11px "Inter", sans-serif', letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-subtle)" }}>Token</span>
              <span style={{ font: '500 11px "Inter", sans-serif', letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-subtle)", textAlign: "right" }}>Amount</span>
              <span style={{ font: '500 11px "Inter", sans-serif', letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-subtle)", textAlign: "right" }}>% of total</span>
            </div>
            {d.collateralRows.map((c, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: "0 16px", padding: "var(--space-8) 0", borderTop: "1px solid var(--border)", alignItems: "center" }}>
                <span><span className="chip chip--info" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{c.token}</span></span>
                <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg)" }}>{c.amount}</span>
                <span className="tnum" style={{ textAlign: "right", font: '500 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{c.pct}%</span>
              </div>
            ))}
            <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "var(--space-12)", marginTop: "var(--space-4)", borderTop: "1px solid var(--border)" }}>
              <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Total value</span>
              <span className="tnum" style={{ font: '600 13px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(d.collateral)}</span>
            </div>
          </MADCard>
          <MADCard title="Debt summary">
            <MADRow label="Principal borrowed" value={fmtMoney(d.borrowed)} />
            <MADRow label="Interest accrued" value={fmtMoney(d.interestAccrued)} tone="var(--gold-70)" />
            <MADRow label="Interest rate" value={`${d.interestRate.toFixed(1)}% APR`} />
            <MADRow label="Daily accrual" value={`~${fmtMoney(d.dailyAccrual)}/day`} />
            <div style={{ display: "flex", justifyContent: "space-between", paddingTop: "var(--space-12)", marginTop: "var(--space-4)", borderTop: "1px solid var(--border)" }}>
              <span style={{ font: '600 14px "Inter", sans-serif', color: "var(--fg)" }}>Total owed</span>
              <span className="tnum" style={{ font: '700 16px "Inter", sans-serif', color: "var(--fg)" }}>{fmtMoney(d.totalOwed)}</span>
            </div>
          </MADCard>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <MADCard title="Account info">
            <MADRow label="Account ID" value={d.id} />
            <MADRow label="Wallet" value={<span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{d.wallet.length > 16 ? d.wallet.slice(0, 8) + "…" + d.wallet.slice(-4) : d.wallet}</span>} />
            <MADRow label="Facility" value={d.facility} />
            <MADRow label="Settlement" value={d.settlement} />
            <MADRow label="Last payment" value={fmtDate(d.lastPayment)} />
            <MADRow label="Next payment" value={fmtDate(d.nextPayment)} />
            <MADRow label="Available credit" value={fmtMoney(d.available)} tone={d.available > 0 ? "var(--fg)" : "var(--fg-faint)"} />
          </MADCard>
          <MADCard title="Admin actions">
            <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-16)" }}>
              Compliance actions on this margin account. DDF liquidation is auto-triggered by searchers, not an admin action.
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-8)" }}>
              {actions.map((a) => (
                <button key={a.key} type="button" onClick={() => onAction(a.key, payload)} style={{
                  height: 40, borderRadius: "var(--radius-md)", cursor: "pointer", font: '600 13px "Inter", sans-serif',
                  display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "var(--space-8)",
                  border: a.primary || a.danger ? "none" : "1px solid var(--border-strong)",
                  background: a.danger ? "var(--danger)" : a.primary ? "var(--accent)" : "var(--surface)",
                  color: a.danger || a.primary ? "var(--white-100)" : "var(--fg)",
                }}><Icon name={a.icon} size={14} stroke={1.7} /> {a.label}</button>
              ))}
            </div>
          </MADCard>
        </div>
      </div>
    </div>
  );
};

window.AdminMarginAccountDetail = AdminMarginAccountDetail;
