/* ===============================================================
   AGENTICS.CREDIT — LENDER DASHBOARD (Stage 5)
   =============================================================== */

const TIER_BLURB = {
  ELITE: "Score 780+ borrowers · lowest yield, lowest risk, fastest fills.",
  QUAL:  "Score 640–779 · balanced risk/yield · the workhorse vault.",
  EMRG:  "Score 540–639 · higher yield from emerging agents in their first 60 days live.",
  SPEC:  "Score < 540 · venture exposure to new strategies · uncorrelated upside.",
};

function LenderDashboard({ account }) {
  // Per-vault user position (mock)
  const [positions, setPositions] = useState({
    ELITE: { shares: 12500, costBasis: 12500, deposited: 12500 },
    QUAL:  { shares:  8000, costBasis:  8000, deposited:  8000 },
    EMRG:  { shares:     0, costBasis:     0, deposited:     0 },
    SPEC:  { shares:     0, costBasis:     0, deposited:     0 },
  });
  const [withdrawals, setWithdrawals] = useState([...MOCK_WITHDRAWALS]);
  const [rewards, setRewards] = useState(MOCK_REWARDS);
  const [tab, setTab] = useState("overview"); // overview | vaults | rewards | withdrawals

  const [depositVault, setDepositVault] = useState(null);
  const [withdrawVault, setWithdrawVault] = useState(null);
  const [vaultDetail, setVaultDetail] = useState(null);

  const toast = useToast();

  // Live tick: rewards accrual + tick down withdrawal countdowns
  useEffect(() => {
    const id = setInterval(() => {
      setRewards(r => ({ ...r, accruing: r.accruing + r.rate * 4 }));
    }, 4000);
    return () => clearInterval(id);
  }, []);

  // Compute aggregate stats based on current positions and pretend share value of 1.012
  const SHARE_VAL = 1.012;
  const totalDeposited = Object.values(positions).reduce((s, p) => s + p.deposited, 0);
  const totalValue     = Object.values(positions).reduce((s, p) => s + p.shares * SHARE_VAL, 0);
  const totalEarned    = totalValue - totalDeposited;
  const blendedApr     = totalDeposited > 0
    ? Object.entries(positions).reduce((s, [k, p]) => {
        const v = TIERS[k];
        return s + (p.deposited / totalDeposited) * v.apr;
      }, 0)
    : 0;

  const handleDeposit = (vaultKey, amount) => {
    setPositions(p => ({
      ...p,
      [vaultKey]: {
        shares:    p[vaultKey].shares    + amount / SHARE_VAL,
        costBasis: p[vaultKey].costBasis + amount,
        deposited: p[vaultKey].deposited + amount,
      },
    }));
    toast?.push({ title: `Deposited ${fmtUSDk(amount)} to lc${vaultKey}`, meta: `${(amount / SHARE_VAL).toFixed(2)} shares minted` });
    setDepositVault(null);
  };

  const handleRequestWithdraw = (vaultKey, amount) => {
    const tier = TIERS[vaultKey];
    const days = tier.lockup || (vaultKey === "ELITE" ? 1 : vaultKey === "QUAL" ? 7 : vaultKey === "EMRG" ? 14 : 30);
    setPositions(p => ({
      ...p,
      [vaultKey]: { ...p[vaultKey], shares: Math.max(0, p[vaultKey].shares - amount / SHARE_VAL) },
    }));
    setWithdrawals(w => [{
      vault: vaultKey,
      shares: amount / SHARE_VAL,
      usdc: amount,
      unlocksAt: Date.now() + days * 24 * 3600 * 1000,
      status: "WAITING",
    }, ...w]);
    toast?.push({ title: `Withdrawal requested · ${fmtUSDk(amount)}`, meta: `Unlocks in ${days}d` });
    setWithdrawVault(null);
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">// LENDER · YIELD</div>
          <h1>Lend capital</h1>
          <div className="muted" style={{ marginTop: 6, fontSize: 13 }}>
            Earn yield by funding scored agents. Pick your risk band — every loan is fully on-chain and rev-share waterfalled daily.
          </div>
        </div>
        <div className="row gap-2">
          <button className="btn btn-ghost btn-sm">↗ READ DOCS</button>
          <button className="btn btn-primary btn-sm" onClick={() => setDepositVault(VAULT_LIST[1])}>+ DEPOSIT USDC</button>
        </div>
      </div>

      {/* PORTFOLIO HEADER */}
      <div className="kpi-strip" style={{ gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 18 }}>
        <div className="kpi">
          <div className="k">PORTFOLIO_VALUE</div>
          <div className="v"><CountUp to={totalValue} fmt={(n) => fmtUSDc(n)}/></div>
          <div className="delta up">+{fmtUSDc(totalEarned)} earned</div>
        </div>
        <div className="kpi">
          <div className="k">DEPLOYED</div>
          <div className="v">{fmtUSDk(totalDeposited)}</div>
          <div className="delta">across {Object.values(positions).filter(p => p.deposited > 0).length} vaults</div>
        </div>
        <div className="kpi">
          <div className="k">BLENDED_APR</div>
          <div className="v accent">{blendedApr.toFixed(2)}%</div>
          <div className="delta up">+ {rewards.rate * 86400 * 7 / 1000} $CREDIT/wk</div>
        </div>
        <div className="kpi">
          <div className="k">$CREDIT_CLAIMABLE</div>
          <div className="v" style={{ color: "var(--accent)" }}>
            <CountUp to={rewards.accruing} fmt={(n) => fmtTok(n)}/>
          </div>
          <div className="delta">accruing live ◎</div>
        </div>
      </div>

      {/* TABS */}
      <div style={{ display: "flex", alignItems: "center", gap: 4, marginBottom: 16, borderBottom: "1px solid var(--border)" }}>
        <LenderTab active={tab === "overview"}    onClick={() => setTab("overview")}    label="OVERVIEW"/>
        <LenderTab active={tab === "vaults"}      onClick={() => setTab("vaults")}      label="ALL_VAULTS"     count={4}/>
        <LenderTab active={tab === "rewards"}     onClick={() => setTab("rewards")}     label="$CREDIT_REWARDS"/>
        <LenderTab active={tab === "withdrawals"} onClick={() => setTab("withdrawals")} label="WITHDRAWALS"    count={withdrawals.length}/>
      </div>

      {tab === "overview" && (
        <Overview
          positions={positions}
          shareVal={SHARE_VAL}
          onDeposit={(v) => setDepositVault(v)}
          onWithdraw={(v) => setWithdrawVault(v)}
          onDetail={(v) => setVaultDetail(v)}
        />
      )}

      {tab === "vaults" && (
        <AllVaults
          positions={positions}
          shareVal={SHARE_VAL}
          onDeposit={(v) => setDepositVault(v)}
          onWithdraw={(v) => setWithdrawVault(v)}
          onDetail={(v) => setVaultDetail(v)}
        />
      )}

      {tab === "rewards" && <RewardsPanel rewards={rewards} setRewards={setRewards} toast={toast}/>}

      {tab === "withdrawals" && (
        <WithdrawalsPanel
          withdrawals={withdrawals}
          setWithdrawals={setWithdrawals}
          toast={toast}
        />
      )}

      {/* Modals */}
      {depositVault && (
        <DepositModal
          vault={depositVault}
          onConfirm={(amt) => handleDeposit(depositVault.key, amt)}
          onClose={() => setDepositVault(null)}
        />
      )}
      {withdrawVault && (
        <WithdrawModal
          vault={withdrawVault}
          position={positions[withdrawVault.key]}
          shareVal={SHARE_VAL}
          onConfirm={(amt) => handleRequestWithdraw(withdrawVault.key, amt)}
          onClose={() => setWithdrawVault(null)}
        />
      )}
      {vaultDetail && (
        <VaultDetailDrawer
          vault={vaultDetail}
          position={positions[vaultDetail.short]}
          shareVal={SHARE_VAL}
          onDeposit={() => { setDepositVault(vaultDetail); setVaultDetail(null); }}
          onWithdraw={() => { setWithdrawVault(vaultDetail); setVaultDetail(null); }}
          onClose={() => setVaultDetail(null)}
        />
      )}

      <style>{lenderStyles}</style>
    </div>
  );
}

/* =============================================================
   OVERVIEW TAB — your active positions + share value chart
   ============================================================= */
function Overview({ positions, shareVal, onDeposit, onWithdraw, onDetail }) {
  const myVaults = VAULT_LIST.filter(v => positions[v.key]?.deposited > 0);
  return (
    <>
      <div className="grid-2" style={{ alignItems: "flex-start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card title="MY_VAULTS">
            {myVaults.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
                No open positions. Deposit into a vault to start earning.
              </div>
            )}
            {myVaults.map(v => {
              const p = positions[v.key];
              const value = p.shares * shareVal;
              const earned = value - p.deposited;
              const earnedPct = (earned / p.deposited) * 100;
              return (
                <div key={v.key} className="my-vault-row" onClick={() => onDetail(v)}>
                  <div className="row gap-3" style={{ alignItems: "center" }}>
                    <span className="vault-tag" style={{ borderColor: v.color, color: v.color }}>lc{v.key}</span>
                    <div>
                      <div className="mono" style={{ fontSize: 13, color: "var(--fg)" }}>{v.label} VAULT</div>
                      <div className="muted f-mono text-xs" style={{ marginTop: 3 }}>~{v.apr}% est. yield · {v.lockup || (v.key === "ELITE" ? 1 : v.key === "QUAL" ? 7 : v.key === "EMRG" ? 14 : 30)}d lockup</div>
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div className="mono" style={{ fontSize: 16, color: "var(--fg)" }}>{fmtUSDc(value)}</div>
                    <div className="mono text-xs" style={{ color: earned >= 0 ? "var(--accent)" : "var(--red)" }}>
                      {earned >= 0 ? "+" : ""}{fmtUSDc(earned)} ({earnedPct >= 0 ? "+" : ""}{earnedPct.toFixed(2)}%)
                    </div>
                  </div>
                  <div className="row gap-2">
                    <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); onDeposit(v); }}>+ ADD</button>
                    <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); onWithdraw(v); }}>− WITHDRAW</button>
                  </div>
                </div>
              );
            })}
          </Card>

          <Card title="UNDERWRITER_HEALTH">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, fontSize: 12, marginBottom: 14 }}>
              <UWStat label="ACTIVE_LOANS" value="47"/>
              <UWStat label="DEFAULT_RATE" value="0.18%" good/>
              <UWStat label="LIQUIDATIONS_30D" value="2"/>
              <UWStat label="PROFIT_SHARE_PAID_30D" value={fmtUSDk(127400)} good/>
            </div>
            <div className="muted text-xs" style={{ fontStyle: "italic" }}>
              Open-ended waterfall: agent gross PnL → 1% borrow fee + 50% profit share to vault → lender share-value accrues daily.
            </div>
          </Card>
        </div>

        <Card title="SHARE_VALUE · 90D">
          <div className="row between" style={{ marginBottom: 12 }}>
            <div>
              <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5 }}>CURRENT_SHARE_VALUE</div>
              <div className="mono" style={{ fontSize: 28, color: "var(--accent)" }}>{shareVal.toFixed(4)}</div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5 }}>90D_RETURN</div>
              <div className="mono" style={{ fontSize: 18, color: "var(--accent)" }}>+ 1.20%</div>
            </div>
          </div>
          <AreaChart data={MOCK_VAULT_HISTORY} height={180} yMin={0.998} yMax={1.05}/>
          <div className="row between" style={{ marginTop: 8, fontSize: 11, color: "var(--muted)", fontFamily: "'DM Mono', monospace" }}>
            <span>DAY 1</span><span>DAY 90</span>
          </div>
          <div style={{ marginTop: 14, padding: 12, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 6, fontSize: 12 }}>
            <div className="row between"><span className="muted">Inception</span><span className="mono">Feb 1, 2026</span></div>
            <div className="row between" style={{ marginTop: 4 }}><span className="muted">All-time peak</span><span className="mono">{shareVal.toFixed(4)}</span></div>
            <div className="row between" style={{ marginTop: 4 }}><span className="muted">Worst drawdown</span><span className="mono">-0.04%</span></div>
          </div>
        </Card>
      </div>
    </>
  );
}

function UWStat({ label, value, good }) {
  return (
    <div style={{ padding: "10px 12px", background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 4 }}>
      <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5, marginBottom: 4 }}>{label}</div>
      <div className="mono" style={{ fontSize: 16, color: good ? "var(--accent)" : "var(--fg)" }}>{value}</div>
    </div>
  );
}

/* =============================================================
   ALL VAULTS TAB — comparison cards
   ============================================================= */
function AllVaults({ positions, shareVal, onDeposit, onWithdraw, onDetail }) {
  return (
    <div className="vault-grid">
      {VAULT_LIST.map(v => {
        const p = positions[v.key] || { deposited: 0, shares: 0 };
        const util = Math.round((v.deposited / v.totalCap) * 100);
        return (
          <div key={v.key} className="vault-card" style={{ borderTop: `2px solid ${v.color}` }} onClick={() => onDetail(v)}>
            <div className="row between" style={{ marginBottom: 14 }}>
              <span className="vault-tag" style={{ borderColor: v.color, color: v.color }}>lc{v.key}</span>
              <TierBadge tier={v}/>
            </div>
            <div className="mono" style={{ fontSize: 32, color: v.color, fontWeight: 500, marginBottom: 4 }}>{v.apr}%</div>
            <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5, marginBottom: 10 }}>EST_NET_YIELD · 30D_TRAILING</div>

            <div className="muted" style={{ fontSize: 12, marginBottom: 14, lineHeight: 1.55, minHeight: 50 }}>{TIER_BLURB[v.key]}</div>

            <div className="vault-stats">
              <div><div className="muted f-mono text-xs">PROFIT_SHARE</div><div className="mono">50%</div></div>
              <div><div className="muted f-mono text-xs">LTV_LIMIT</div><div className="mono">{v.ltv}%</div></div>
              <div><div className="muted f-mono text-xs">LOCKUP</div><div className="mono">{v.key === "ELITE" ? "1d" : v.key === "QUAL" ? "7d" : v.key === "EMRG" ? "14d" : "30d"}</div></div>
              <div><div className="muted f-mono text-xs">MAX_LOAN</div><div className="mono">{fmtUSDk(v.maxLoan)}</div></div>
            </div>

            <div style={{ marginTop: 14 }}>
              <div className="row between" style={{ marginBottom: 4, fontSize: 11, color: "var(--muted)" }}>
                <span className="f-mono">UTILISATION</span>
                <span className="mono">{util}%</span>
              </div>
              <ProgressBar value={util} color={v.color}/>
              <div className="row between" style={{ marginTop: 6, fontSize: 11, color: "var(--muted)" }}>
                <span className="f-mono">{fmtUSDk(v.deposited)} / {fmtUSDk(v.totalCap)}</span>
                <span className="f-mono">{fmtUSDk(v.available)} avail</span>
              </div>
            </div>

            {p.deposited > 0 && (
              <div style={{ marginTop: 14, padding: 10, background: "var(--card-tint-2)", border: "1px solid var(--accent)", borderRadius: 4, fontSize: 12 }}>
                <div className="row between"><span className="muted">YOUR POSITION</span><span className="mono accent">{fmtUSDc(p.shares * shareVal)}</span></div>
              </div>
            )}

            <div className="row gap-2" style={{ marginTop: 14 }}>
              <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={(e) => { e.stopPropagation(); onDeposit(v); }}>DEPOSIT →</button>
              {p.deposited > 0 && <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); onWithdraw(v); }}>−</button>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* =============================================================
   REWARDS TAB — $CREDIT vesting + claim
   ============================================================= */
function RewardsPanel({ rewards, setRewards, toast }) {
  const handleClaim = () => {
    const amt = rewards.claimable;
    setRewards(r => ({ ...r, claimable: 0 }));
    toast?.push({ title: `Claimed ${fmtTok(amt)} $CREDIT`, meta: "Sent to your wallet" });
  };
  return (
    <div className="grid-2" style={{ alignItems: "flex-start" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card title="$CREDIT_REWARDS" glow>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 16 }}>
            <div className="reward-cell">
              <div className="muted f-mono text-xs">ACCRUING</div>
              <div className="mono" style={{ fontSize: 22, color: "var(--accent)" }}>
                <CountUp to={rewards.accruing} fmt={(n) => fmtTok(n)}/>
              </div>
              <div className="muted text-xs" style={{ marginTop: 2 }}>+{rewards.rate.toFixed(3)}/sec</div>
            </div>
            <div className="reward-cell">
              <div className="muted f-mono text-xs">VESTING</div>
              <div className="mono" style={{ fontSize: 22, color: "var(--fg)" }}>{fmtTok(rewards.vesting)}</div>
              <div className="muted text-xs" style={{ marginTop: 2 }}>{rewards.vestingDay}/{rewards.vestingTotal}d</div>
            </div>
            <div className="reward-cell">
              <div className="muted f-mono text-xs">CLAIMABLE</div>
              <div className="mono" style={{ fontSize: 22, color: rewards.claimable > 0 ? "var(--accent)" : "var(--muted)" }}>{fmtTok(rewards.claimable)}</div>
              <div className="muted text-xs" style={{ marginTop: 2 }}>ready to claim</div>
            </div>
          </div>

          <div style={{ marginTop: 8 }}>
            <div className="row between" style={{ marginBottom: 6, fontSize: 11, color: "var(--muted)" }}>
              <span className="f-mono">VESTING_PROGRESS</span>
              <span className="mono">{Math.round((rewards.vestingDay / rewards.vestingTotal) * 100)}%</span>
            </div>
            <ProgressBar value={(rewards.vestingDay / rewards.vestingTotal) * 100}/>
          </div>

          <button
            className="btn btn-primary btn-block btn-lg"
            style={{ marginTop: 18 }}
            onClick={handleClaim}
            disabled={rewards.claimable <= 0}
          >
            CLAIM {fmtTok(rewards.claimable)} $CREDIT →
          </button>
        </Card>

        <Card title="HOW_REWARDS_WORK">
          <ol style={{ margin: 0, padding: "0 0 0 18px", color: "var(--fg-dim)", fontSize: 12, lineHeight: 1.85 }}>
            <li>Lenders accrue $CREDIT every block proportional to deposited capital × tier multiplier.</li>
            <li>SPEC vault earns 4× the base rate; EMRG 2.5×; QUAL 1.5×; ELITE 1×.</li>
            <li>Accruing → Vesting on Sunday UTC midnight. 180-day linear vest.</li>
            <li>$CREDIT can be staked, used to boost agent credit lines, or held for governance.</li>
          </ol>
        </Card>
      </div>

      <Card title="$CREDIT_PRICE · 30D">
        <div className="row between" style={{ marginBottom: 12 }}>
          <div>
            <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5 }}>SPOT</div>
            <div className="mono" style={{ fontSize: 28, color: "var(--accent)" }}>$1.42</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div className="muted f-mono text-xs" style={{ letterSpacing: 1.5 }}>30D</div>
            <div className="mono" style={{ fontSize: 18, color: "var(--accent)" }}>+ 23.7%</div>
          </div>
        </div>
        <AreaChart data={MOCK_VAULT_HISTORY.slice(-30).map((p, i) => ({ x: i, y: 1.15 + Math.sin(i * 0.4) * 0.1 + i * 0.008 }))} height={160} yMin={1.0} yMax={1.5}/>
        <div style={{ marginTop: 14, padding: 12, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 6, fontSize: 12 }}>
          <div className="row between"><span className="muted">Total supply</span><span className="mono">100M</span></div>
          <div className="row between" style={{ marginTop: 4 }}><span className="muted">Circulating</span><span className="mono">12.4M</span></div>
          <div className="row between" style={{ marginTop: 4 }}><span className="muted">Holders</span><span className="mono">2,341</span></div>
        </div>
      </Card>
    </div>
  );
}

/* =============================================================
   WITHDRAWALS TAB
   ============================================================= */
function WithdrawalsPanel({ withdrawals, setWithdrawals, toast }) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => { const id = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(id); }, []);

  const claim = (i) => {
    const w = withdrawals[i];
    setWithdrawals(ws => ws.filter((_, idx) => idx !== i));
    toast?.push({ title: `Claimed ${fmtUSDc(w.usdc)} from lc${w.vault}`, meta: "USDC sent to your wallet" });
  };

  return (
    <Card title="ACTIVE_WITHDRAWAL_REQUESTS">
      {withdrawals.length === 0 && (
        <div style={{ padding: 24, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
          No pending withdrawals. Request one from any of your open positions.
        </div>
      )}
      {withdrawals.length > 0 && (
        <table className="tbl">
          <thead>
            <tr>
              <th>VAULT</th><th className="num">SHARES</th><th className="num">USDC_OUT</th>
              <th>STATUS</th><th>UNLOCK_IN</th><th></th>
            </tr>
          </thead>
          <tbody>
            {withdrawals.map((w, i) => {
              const ms = w.unlocksAt - now;
              const ready = ms <= 0;
              return (
                <tr key={i}>
                  <td><span className="vault-tag" style={{ borderColor: TIERS[w.vault].color, color: TIERS[w.vault].color }}>lc{w.vault}</span></td>
                  <td className="num mono">{Number(w.shares).toLocaleString(undefined, { maximumFractionDigits: 2 })}</td>
                  <td className="num mono">{fmtUSDc(w.usdc)}</td>
                  <td><span className="mono" style={{ color: ready ? "var(--accent)" : (ms < 6 * 3600 * 1000 ? "var(--amber)" : "var(--muted)"), fontSize: 11 }}>{ready ? "● READY" : (ms < 6 * 3600 * 1000 ? "● READY_SOON" : "○ WAITING")}</span></td>
                  <td className="mono">{ready ? "—" : fmtCountdown(ms)}</td>
                  <td className="num">
                    {ready
                      ? <button className="btn btn-primary btn-sm" onClick={() => claim(i)}>CLAIM →</button>
                      : <button className="btn btn-ghost btn-sm" disabled>CLAIM</button>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
      <div className="muted text-xs" style={{ marginTop: 14, fontStyle: "italic" }}>
        Lockups protect agents from sudden capital pulls. ELITE: 1d · QUAL: 7d · EMRG: 14d · SPEC: 30d.
      </div>
    </Card>
  );
}

/* =============================================================
   DEPOSIT MODAL
   ============================================================= */
function DepositModal({ vault, onConfirm, onClose }) {
  const [amount, setAmount] = useState(10000);
  const [step, setStep] = useState("review"); // review | approve | confirm
  const usdcBalance = 84_320;
  const shares = amount / 1.012;
  const yearProj = amount * (vault.apr / 100);

  const lockupDays = vault.key === "ELITE" ? 1 : vault.key === "QUAL" ? 7 : vault.key === "EMRG" ? 14 : 30;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ width: 560 }} onClick={(e) => e.stopPropagation()}>
        <div className="row between" style={{ marginBottom: 14 }}>
          <div>
            <div className="label-mono">// DEPOSIT_USDC</div>
            <div className="mono" style={{ fontSize: 18, color: "var(--fg)", marginTop: 4 }}>
              <span style={{ color: vault.color }}>lc{vault.key}</span> · {vault.label} VAULT
            </div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>CLOSE ×</button>
        </div>

        <div style={{ background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 6, padding: 16, marginBottom: 14 }}>
          <div className="row between" style={{ marginBottom: 8 }}>
            <span className="muted f-mono text-xs">AMOUNT (USDC)</span>
            <button className="btn btn-ghost btn-sm" onClick={() => setAmount(usdcBalance)}>MAX</button>
          </div>
          <input
            type="number"
            className="amount-input"
            value={amount}
            onChange={(e) => setAmount(Math.min(Number(e.target.value) || 0, usdcBalance))}
          />
          <div className="row between" style={{ marginTop: 8, fontSize: 11, color: "var(--muted)" }}>
            <span className="f-mono">BALANCE</span>
            <span className="mono">{fmtUSDc(usdcBalance)} USDC</span>
          </div>
          <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
            {[0.25, 0.5, 0.75, 1].map(p => (
              <button key={p} className="btn btn-ghost btn-sm" style={{ flex: 1 }} onClick={() => setAmount(Math.round(usdcBalance * p))}>{p === 1 ? "MAX" : `${p * 100}%`}</button>
            ))}
          </div>
        </div>

        <div style={{ background: "var(--card-tint)", border: "1px solid var(--border-2)", borderRadius: 6, padding: 14, marginBottom: 14, display: "flex", flexDirection: "column", gap: 6, fontSize: 12 }}>
          <div className="row between"><span className="muted">You receive</span><span className="mono accent">{fmtTok(shares)} lc{vault.key}-shares</span></div>
          <div className="row between"><span className="muted">Estimated yield</span><span className="mono accent">{vault.apr}% · 30d trailing</span></div>
          <div className="row between"><span className="muted">12mo projection</span><span className="mono">+{fmtUSDc(yearProj)}</span></div>
          <div className="row between"><span className="muted">Lockup on withdraw</span><span className="mono">{lockupDays}d</span></div>
          <div className="row between"><span className="muted">Network</span><span className="mono">Ethereum mainnet</span></div>
          <div className="row between"><span className="muted">Gas estimate</span><span className="mono">~$3.40</span></div>
        </div>

        <div style={{ background: "var(--bg)", border: "1px solid var(--amber)", borderRadius: 6, padding: 12, marginBottom: 14, fontSize: 11 }}>
          <div className="row gap-2">
            <span style={{ color: "var(--amber)", fontFamily: "'DM Mono', monospace" }}>!</span>
            <span style={{ color: "var(--fg-dim)", lineHeight: 1.6 }}>
              Capital is loaned to scored agents. Default risk is mitigated by tier-banded LTV, daily settlements, and waterfall protections — but is non-zero. Read the {vault.label} risk disclosure.
            </span>
          </div>
        </div>

        {step === "review" && (
          <button className="btn btn-primary btn-block btn-lg" onClick={() => setStep("approve")} disabled={amount <= 0}>
            REVIEW DEPOSIT →
          </button>
        )}
        {step === "approve" && (
          <button className="btn btn-primary btn-block btn-lg" onClick={() => setStep("confirm")}>
            ✓ APPROVE {fmtUSDc(amount)} USDC SPEND
          </button>
        )}
        {step === "confirm" && (
          <button className="btn btn-primary btn-block btn-lg" onClick={() => onConfirm(amount)}>
            CONFIRM DEPOSIT · SIGN TX
          </button>
        )}

        <div style={{ display: "flex", gap: 8, marginTop: 12, justifyContent: "center" }}>
          <StepDot active={step === "review"} done={step !== "review"}>1 · Review</StepDot>
          <StepDot active={step === "approve"} done={step === "confirm"}>2 · Approve</StepDot>
          <StepDot active={step === "confirm"}>3 · Sign</StepDot>
        </div>
      </div>
    </div>
  );
}

function StepDot({ active, done, children }) {
  return (
    <span className="mono" style={{
      fontSize: 10, padding: "4px 10px", borderRadius: 999,
      background: active ? "var(--accent)" : (done ? "var(--card-tint-2)" : "var(--bg)"),
      color: active ? "var(--bg)" : (done ? "var(--accent)" : "var(--muted)"),
      border: "1px solid " + (active || done ? "var(--accent)" : "var(--border)"),
      letterSpacing: 1,
    }}>{children}</span>
  );
}

/* =============================================================
   WITHDRAW MODAL
   ============================================================= */
function WithdrawModal({ vault, position, shareVal, onConfirm, onClose }) {
  const maxUsdc = position.shares * shareVal;
  const [amount, setAmount] = useState(Math.min(5000, Math.round(maxUsdc)));
  const lockupDays = vault.key === "ELITE" ? 1 : vault.key === "QUAL" ? 7 : vault.key === "EMRG" ? 14 : 30;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ width: 520 }} onClick={(e) => e.stopPropagation()}>
        <div className="row between" style={{ marginBottom: 14 }}>
          <div>
            <div className="label-mono">// REQUEST_WITHDRAWAL</div>
            <div className="mono" style={{ fontSize: 18, color: "var(--fg)", marginTop: 4 }}>
              <span style={{ color: vault.color }}>lc{vault.key}</span>
            </div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>CLOSE ×</button>
        </div>

        <div style={{ background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 6, padding: 16, marginBottom: 14 }}>
          <div className="row between" style={{ marginBottom: 8 }}>
            <span className="muted f-mono text-xs">USDC TO WITHDRAW</span>
            <button className="btn btn-ghost btn-sm" onClick={() => setAmount(Math.round(maxUsdc))}>MAX</button>
          </div>
          <input
            type="number"
            className="amount-input"
            value={amount}
            onChange={(e) => setAmount(Math.min(Number(e.target.value) || 0, Math.round(maxUsdc)))}
          />
          <div className="row between" style={{ marginTop: 8, fontSize: 11, color: "var(--muted)" }}>
            <span className="f-mono">POSITION_VALUE</span>
            <span className="mono">{fmtUSDc(maxUsdc)}</span>
          </div>
        </div>

        <div style={{ background: "var(--card-tint)", border: "1px solid var(--border-2)", borderRadius: 6, padding: 14, marginBottom: 14, display: "flex", flexDirection: "column", gap: 6, fontSize: 12 }}>
          <div className="row between"><span className="muted">Shares burned</span><span className="mono">{(amount / shareVal).toFixed(2)}</span></div>
          <div className="row between"><span className="muted">Lockup window</span><span className="mono accent">{lockupDays} days</span></div>
          <div className="row between"><span className="muted">Funds available</span><span className="mono">{new Date(Date.now() + lockupDays * 86400000).toLocaleDateString()}</span></div>
          <div className="row between"><span className="muted">Continuing rev share</span><span className="mono">until unlock</span></div>
        </div>

        <button className="btn btn-primary btn-block btn-lg" onClick={() => onConfirm(amount)} disabled={amount <= 0}>
          REQUEST WITHDRAWAL · SIGN TX
        </button>
        <div className="muted text-xs" style={{ marginTop: 10, textAlign: "center" }}>
          Capital remains in the vault and continues earning until the lockup expires.
        </div>
      </div>
    </div>
  );
}

/* =============================================================
   VAULT DETAIL DRAWER
   ============================================================= */
function VaultDetailDrawer({ vault, position, shareVal, onDeposit, onWithdraw, onClose }) {
  const value = position?.shares * shareVal || 0;
  const earned = value - (position?.deposited || 0);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="drawer" onClick={(e) => e.stopPropagation()}>
        <div className="row between" style={{ marginBottom: 18 }}>
          <div>
            <div className="label-mono">// VAULT_DETAIL</div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 6 }}>
              <span className="vault-tag" style={{ borderColor: vault.color, color: vault.color, fontSize: 14, padding: "6px 14px" }}>lc{vault.key}</span>
              <div className="mono" style={{ fontSize: 22, color: "var(--fg)" }}>{vault.label} VAULT</div>
            </div>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>CLOSE ×</button>
        </div>

        <div className="grid-2" style={{ alignItems: "flex-start" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Card title="VAULT_TERMS">
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <DrawerStat label="EST_YIELD"   value={`${vault.apr}%`}/>
                <DrawerStat label="PROFIT_SHARE" value={`50%`}/>
                <DrawerStat label="LTV_LIMIT"   value={`${vault.ltv}%`}/>
                <DrawerStat label="LOCKUP"      value={`${vault.key === "ELITE" ? 1 : vault.key === "QUAL" ? 7 : vault.key === "EMRG" ? 14 : 30}d`}/>
                <DrawerStat label="MAX_LOAN"    value={fmtUSDk(vault.maxLoan)}/>
                <DrawerStat label="UTILISATION" value={`${Math.round((vault.deposited / vault.totalCap) * 100)}%`}/>
              </div>
              <div style={{ marginTop: 14, fontSize: 12, color: "var(--fg-dim)", lineHeight: 1.6 }}>
                {TIER_BLURB[vault.key]}
              </div>
            </Card>

            <Card title="MY_POSITION">
              <div className="row between" style={{ padding: "6px 0", fontSize: 13 }}>
                <span className="muted">Deposited</span>
                <span className="mono">{fmtUSDc(position?.deposited || 0)}</span>
              </div>
              <div className="row between" style={{ padding: "6px 0", fontSize: 13 }}>
                <span className="muted">Current value</span>
                <span className="mono accent">{fmtUSDc(value)}</span>
              </div>
              <div className="row between" style={{ padding: "6px 0", fontSize: 13 }}>
                <span className="muted">Unrealised PnL</span>
                <span className="mono" style={{ color: earned >= 0 ? "var(--accent)" : "var(--red)" }}>{earned >= 0 ? "+" : ""}{fmtUSDc(earned)}</span>
              </div>
              <div className="row between" style={{ padding: "6px 0", fontSize: 13 }}>
                <span className="muted">Shares</span>
                <span className="mono">{Number(position?.shares || 0).toFixed(2)}</span>
              </div>
              <div className="row gap-2" style={{ marginTop: 14 }}>
                <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={onDeposit}>+ DEPOSIT</button>
                {position?.deposited > 0 && <button className="btn btn-secondary btn-sm" style={{ flex: 1 }} onClick={onWithdraw}>− WITHDRAW</button>}
              </div>
            </Card>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Card title="SHARE_VALUE · 90D">
              <AreaChart data={MOCK_VAULT_HISTORY} height={140} yMin={0.998} yMax={1.05}/>
              <div className="row between" style={{ marginTop: 8, fontSize: 11, color: "var(--muted)", fontFamily: "'DM Mono', monospace" }}>
                <span>1.0000</span><span>{shareVal.toFixed(4)}</span>
              </div>
            </Card>

            <Card title="ACTIVE_BORROWERS">
              {MOCK_LEADERBOARD.filter(r => r.tier.short === vault.key && r.loan).slice(0, 5).map(r => (
                <div key={r.rank} className="row between" style={{ padding: "8px 0", borderBottom: "1px dashed var(--border)", fontSize: 12 }}>
                  <div>
                    <div className="mono" style={{ color: "var(--fg-dim)" }}>{r.addr}</div>
                    <div className="muted f-mono text-xs" style={{ marginTop: 2 }}>SCORE {r.score} · DAY {r.day}</div>
                  </div>
                  <span className="mono accent">{fmtUSDk(r.loan)}</span>
                </div>
              ))}
              {MOCK_LEADERBOARD.filter(r => r.tier.short === vault.key && r.loan).length === 0 && (
                <div className="muted" style={{ fontSize: 12, padding: 12, textAlign: "center" }}>No active borrowers in this vault yet.</div>
              )}
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

/* =============================================================
   STYLES
   ============================================================= */
function LenderTab({ active, onClick, label, count }) {
  return (
    <button onClick={onClick} style={{
      padding: "10px 16px",
      background: active ? "var(--bg-2)" : "transparent",
      border: "1px solid " + (active ? "var(--border)" : "transparent"),
      borderBottom: active ? "1px solid var(--bg-2)" : "1px solid var(--border)",
      borderRadius: "6px 6px 0 0",
      color: active ? "var(--accent)" : "var(--muted)",
      fontFamily: "'DM Mono', monospace",
      fontSize: 11, letterSpacing: 1,
      cursor: "pointer",
      marginBottom: -1,
    }}>
      {label}{count != null && <span className="muted" style={{ marginLeft: 6 }}>({count})</span>}
    </button>
  );
}

const lenderStyles = `
.vault-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }
.vault-card { background: var(--bg-2); border: 1px solid var(--border-2); border-radius: 8px; padding: 20px; cursor: pointer; transition: all .15s ease; display: flex; flex-direction: column; }
.vault-card:hover { border-color: var(--accent); transform: translateY(-2px); }

.vault-tag { display: inline-block; padding: 4px 10px; border: 1px solid; border-radius: 4px; font-family: 'DM Mono', monospace; font-size: 11px; letter-spacing: 1px; background: var(--bg); }

.vault-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 12px; padding: 12px 0; border-top: 1px dashed var(--border); border-bottom: 1px dashed var(--border); margin-top: 6px; }
.vault-stats .mono { font-size: 13px; color: var(--fg); margin-top: 2px; }

.my-vault-row { display: grid; grid-template-columns: 1.4fr 1fr auto; gap: 16px; align-items: center; padding: 14px; border-bottom: 1px solid var(--border); cursor: pointer; transition: background .1s ease; }
.my-vault-row:hover { background: var(--card-tint); }
.my-vault-row:last-child { border-bottom: none; }

.reward-cell { padding: 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 4px; }

.amount-input { width: 100%; background: transparent; border: none; color: var(--fg); font-family: 'DM Mono', monospace; font-size: 28px; outline: none; padding: 4px 0; }
.amount-input::-webkit-outer-spin-button, .amount-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.amount-input { -moz-appearance: textfield; }
`;

Object.assign(window, { LenderDashboard });
