// LenderDashboard.jsx — Lend → Lender dashboard (B13).
//
// Fills the former nav stub with the supply-side view: deposited stablecoins
// and yield (KPI summary), the protocol reserve & protection status, and the
// lender's positions table (paginated). Seeded from LENDER_DATA, which extends
// PORTFOLIO_DATA.lendingPositions.
//
// Reuses HeroKPI / SupportKPI (from Portfolio.jsx) and Pagination (from
// Primitives.jsx) for visual consistency with the rest of the app.

// ── Reserve & protection ────────────────────────────────────────────────────
const ReserveProtection = ({ reserve }) => {
  const committedPct = 100 - reserve.availablePct;
  return (
    <section className="card" style={{ padding: "var(--space-24)" }} data-annot-note="B13 reserve & protection">
      <Eyebrow>Reserve &amp; protection</Eyebrow>
      <h2 className="section-heading" style={{ marginTop: "var(--space-8)", marginBottom: "var(--space-4)" }}>Protocol reserve status</h2>
      <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-20)", maxWidth: 620 }}>
        The reserve backs lender deposits against shortfalls. A coverage ratio above
        the 1.0x floor means committed protection exceeds outstanding risk.
      </div>

      <div className="kpi-strip" style={{
        display: "flex", flexWrap: "wrap",
        border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", overflow: "hidden",
      }}>
        <SupportKPI label="Total reserve"      value={reserve.total}     sub={reserve.totalSub} tone="success" />
        <SupportKPI label="Available capacity" value={reserve.available} sub={reserve.availableSub} />
        <SupportKPI label="Committed"          value={reserve.committed} sub={reserve.committedSub} tone="warning" />
        <SupportKPI label="Coverage ratio"     value={reserve.coverage}  sub={reserve.coverageSub} tone="success" last />
      </div>

      {/* Capacity utilization bar */}
      <div style={{ marginTop: "var(--space-20)" }}>
        <div style={{
          display: "flex", justifyContent: "space-between",
          font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)",
        }}>
          <span>Capacity in use</span>
          <span className="tnum">{committedPct}% committed · {reserve.availablePct}% available</span>
        </div>
        <div style={{ height: 6, background: "var(--black-20)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
          <div style={{ width: committedPct + "%", height: "100%", background: "var(--gold-60)", borderRadius: "var(--radius-sm)" }} />
        </div>
      </div>
    </section>
  );
};

// ── Lender flow modal (deposit + withdraw) ──────────────────────────────────
const LenderFlowModal = ({ type, pools = [], positions = [], prefillPool, prefillPosition, onClose }) => {
  const [step, setStep] = React.useState(prefillPool || prefillPosition ? 1 : 0);
  const [selectedPool, setSelectedPool] = React.useState(prefillPool || null);
  const [selectedPosition, setSelectedPosition] = React.useState(prefillPosition || null);
  const [amount, setAmount] = React.useState("");
  const [done, setDone] = React.useState(false);

  // Escape closes the flow, matching the backdrop-click and Cancel affordances.
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const isDeposit = type === "deposit";
  const item = isDeposit ? selectedPool : selectedPosition;
  const mockTxHash = "0x9f2a" + (item ? (item.id || item.name || "").replace(/[^a-z0-9]/gi, "").slice(0, 8) : "flow1234") + "c4b9";

  const estYield = amount && item && item.apy
    ? "$" + (parseFloat(amount.replace(/,/g, "")) * (parseFloat(item.apy) / 100)).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " / yr"
    : "—";

  if (done) {
    return (
      <div role="dialog" aria-modal="true" aria-labelledby="lf-title" style={{ position: "fixed", inset: 0, zIndex: 100, display: "grid", placeItems: "center", background: "var(--scrim)", animation: "fade 150ms ease-out" }} onClick={onClose}>
        <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--surface)", width: 480, maxWidth: "calc(100vw - 32px)", borderRadius: "var(--radius-xl)", padding: "var(--space-24)", boxShadow: "var(--shadow-1)", animation: "rise 150ms ease-out" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "var(--space-16)", marginBottom: "var(--space-20)" }}>
            <div style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--green-10)", color: "var(--success)", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name="shieldCheck" size={20} stroke={1.5} />
            </div>
            <div>
              <h2 id="lf-title" style={{ margin: 0, font: '700 20px/26px "Figtree", sans-serif', color: "var(--fg)" }}>
                {isDeposit ? "Deposit submitted" : "Withdrawal submitted"}
              </h2>
              <div style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-4)" }}>
                Transaction is awaiting on-chain confirmation.
              </div>
            </div>
          </div>
          <div style={{ padding: "var(--space-16) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)", display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: "var(--space-12)", columnGap: "var(--space-16)", marginBottom: "var(--space-20)" }}>
            {[
              { label: "Pool", value: item?.name || "—" },
              { label: "Amount", value: amount ? "$" + parseFloat(amount.replace(/,/g, "")).toLocaleString() : "—" },
              isDeposit ? { label: "Est. annual yield", value: estYield } : { label: "Settles", value: item?.settles || "USDC" },
              { label: "Transaction", value: mockTxHash, mono: true },
            ].map(({ label, value, mono }) => (
              <div key={label} style={mono ? { gridColumn: "1 / -1" } : {}}>
                <div style={{ font: '400 10px/14px "Inter", sans-serif', letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-2)" }}>{label}</div>
                <div className={mono ? "addr tnum" : "tnum"} style={{ font: mono ? '500 12px/16px "JetBrains Mono", monospace' : '500 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{value}</div>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <button className="btn btn--primary" type="button" onClick={onClose}>Done</button>
          </div>
        </div>
        <style>{`@keyframes fade { from { opacity: 0 } to { opacity: 1 } } @keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }`}</style>
      </div>
    );
  }

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="lf-title" style={{ position: "fixed", inset: 0, zIndex: 100, display: "grid", placeItems: "center", background: "var(--scrim)", animation: "fade 150ms ease-out" }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--surface)", width: 500, maxWidth: "calc(100vw - 32px)", borderRadius: "var(--radius-xl)", padding: "var(--space-24)", boxShadow: "var(--shadow-1)", animation: "rise 150ms ease-out", maxHeight: "calc(100vh - 48px)", overflowY: "auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "var(--space-20)" }}>
          <div>
            <Eyebrow>Lend</Eyebrow>
            <h2 id="lf-title" style={{ margin: "var(--space-4) 0 0", font: '700 20px/26px "Figtree", sans-serif', color: "var(--fg)" }}>
              {isDeposit ? "Deposit stablecoins" : "Withdraw stablecoins"}
            </h2>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ all: "unset", cursor: "pointer", padding: "var(--space-8)", color: "var(--fg-subtle)" }}>
            <Icon name="cross" size={16} stroke={1.6} />
          </button>
        </div>

        {/* Step 0: Pool / position picker */}
        {step === 0 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-8)" }}>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
              {isDeposit ? "Select the lending pool to deposit into." : "Select a position to withdraw from."}
            </div>
            {(isDeposit ? pools : positions.filter(p => !(/paused/i.test(p.name)))).map((item) => (
              <button key={item.id || item.name} type="button" onClick={() => { isDeposit ? setSelectedPool(item) : setSelectedPosition(item); }} style={{
                all: "unset", cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "var(--space-16) var(--space-16)", borderRadius: "var(--radius-lg)",
                border: (isDeposit ? selectedPool?.id === item.id : selectedPosition?.name === item.name) ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                background: (isDeposit ? selectedPool?.id === item.id : selectedPosition?.name === item.name) ? "var(--blue-10)" : "var(--bg-alt)",
                transition: "border-color var(--motion-fast), background var(--motion-fast)",
              }}>
                <div>
                  <div style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{item.name}</div>
                  <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-2)" }}>
                    {item.tranche} · {item.settles} · APY {item.apy} · {isDeposit ? "TVL " + item.tvl : "Value " + item.currentValue}
                  </div>
                </div>
                <div style={{ width: 18, height: 18, borderRadius: "50%", border: "2px solid", borderColor: (isDeposit ? selectedPool?.id === item.id : selectedPosition?.name === item.name) ? "var(--accent)" : "var(--border)", background: (isDeposit ? selectedPool?.id === item.id : selectedPosition?.name === item.name) ? "var(--accent)" : "transparent", flexShrink: 0 }} />
              </button>
            ))}
          </div>
        )}

        {/* Step 1: Amount */}
        {step === 1 && (
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
            <div style={{ padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
              <div style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{item?.name}</div>
              <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-2)" }}>
                {item?.tranche} · {item?.settles} · APY {item?.apy}
              </div>
            </div>
            {!isDeposit && item && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-12)" }}>
                {[
                  { label: "Deposited", value: item.deposited },
                  { label: "Earned yield", value: "+" + item.earnedYield, color: "var(--success)" },
                ].map(({ label, value, color }) => (
                  <div key={label} style={{ padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
                    <div style={{ font: '400 11px/14px "Inter", sans-serif', letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-4)" }}>{label}</div>
                    <div className="tnum" style={{ font: '600 16px/22px "Figtree", sans-serif', color: color || "var(--fg)" }}>{value}</div>
                  </div>
                ))}
              </div>
            )}
            <div>
              <label style={{ display: "block", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
                Amount ({item?.settles || "USDC"})
              </label>
              <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", padding: "0 var(--space-12)" }}>
                <input
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  inputMode="decimal"
                  placeholder="0.00"
                  style={{ flex: 1, border: 0, outline: 0, font: '500 22px/30px "Figtree", sans-serif', color: "var(--fg)", background: "transparent", padding: "var(--space-12) 0", fontVariantNumeric: "tabular-nums" }}
                />
                <span className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-8)" }}>{item?.settles || "USDC"}</span>
                <button className="btn btn--ghost btn--sm" type="button" onClick={() => setAmount(!isDeposit && item ? item.deposited.replace("$", "").replace(/,/g, "") : "MAX")}>MAX</button>
              </div>
            </div>
            {isDeposit && (
              <div style={{ display: "flex", justifyContent: "space-between", padding: "var(--space-12) var(--space-16)", background: "var(--bg-alt)", borderRadius: "var(--radius-md)" }}>
                <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>Est. annual yield</span>
                <span className="tnum" style={{ font: '600 13px/18px "Inter", sans-serif', color: "var(--success)" }}>{estYield}</span>
              </div>
            )}
          </div>
        )}

        <div style={{ display: "flex", gap: "var(--space-8)", justifyContent: "space-between", marginTop: "var(--space-24)" }}>
          <div>{step > 0 && !prefillPool && !prefillPosition && <button className="btn btn--secondary" type="button" onClick={() => setStep(0)}>Back</button>}</div>
          <div style={{ display: "flex", gap: "var(--space-8)" }}>
            <button className="btn btn--secondary" type="button" onClick={onClose}>Cancel</button>
            {step === 0 ? (
              <button className="btn btn--primary" type="button" disabled={!(isDeposit ? selectedPool : selectedPosition)} onClick={() => setStep(1)}>
                Next <Icon name="arrow" size={13} stroke={1.6} />
              </button>
            ) : (
              <button className="btn btn--primary" type="button" onClick={() => setDone(true)}>
                {isDeposit ? "Deposit" : "Withdraw"}
                <Icon name="arrow" size={13} stroke={1.6} />
              </button>
            )}
          </div>
        </div>
      </div>
      <style>{`@keyframes fade { from { opacity: 0 } to { opacity: 1 } } @keyframes rise { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }`}</style>
    </div>
  );
};

// ── Positions table (paginated) ─────────────────────────────────────────────
const LenderPositionsTable = ({ positions, onDeposit, onWithdraw }) => {
  const [page, setPage] = React.useState(1);
  const [perPage, setPerPage] = React.useState(6);
  const pageCount = Math.max(1, Math.ceil(positions.length / perPage));
  const safePage = Math.min(page, pageCount);
  const rows = positions.slice((safePage - 1) * perPage, safePage * perPage);
  const cols = "minmax(170px, 1.6fr) 1fr 1fr 0.6fr 0.9fr 1fr 1fr auto";

  return (
    <section className="card" style={{ padding: 0 }} data-annot-note="B13 lender positions">
      <div style={{ padding: "var(--space-20) var(--space-24) var(--space-16)", display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: "var(--space-12)", flexWrap: "wrap" }}>
        <div>
          <Eyebrow>Lend</Eyebrow>
          <h2 className="section-heading" style={{ marginTop: "var(--space-8)" }}>
            Your positions
            <span style={{
              display: "inline-block", marginLeft: "var(--space-12)",
              font: '500 14px/20px "Inter", sans-serif',
              color: "var(--fg-subtle)", verticalAlign: "middle",
            }}>{positions.length}</span>
          </h2>
        </div>
      </div>

      <div className="fac-scroll">
        <div className="fac-head" style={{
          display: "grid", gridTemplateColumns: cols,
          padding: "var(--space-8) var(--space-24)",
          borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)",
          background: "var(--bg-alt)",
          font: '500 11px/16px "Inter", sans-serif',
          letterSpacing: "0.04em", textTransform: "uppercase",
          color: "var(--fg-subtle)", gap: "var(--space-12)",
        }}>
          <span>Pool</span>
          <span style={{ textAlign: "right" }}>Deposited</span>
          <span style={{ textAlign: "right" }}>LP tokens</span>
          <span style={{ textAlign: "right" }}>APY</span>
          <span style={{ textAlign: "right" }}>Earned</span>
          <span style={{ textAlign: "right" }}>Value</span>
          <span style={{ textAlign: "right" }}>Withdrawable</span>
          <span></span>
        </div>

        {rows.map((p, i) => {
          const paused = /paused/i.test(p.name);
          return (
            <div key={p.name} style={{
              display: "grid", gridTemplateColumns: cols,
              padding: "var(--space-16) var(--space-24)",
              borderTop: i === 0 ? "none" : "1px solid var(--border)",
              gap: "var(--space-12)", alignItems: "center",
            }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: "var(--space-8)", flexWrap: "wrap" }}>
                  <span style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{p.name}</span>
                  {paused && <StatusPill variant="paused">Paused</StatusPill>}
                </div>
                <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
                  {p.tranche} · Settles {p.settles}
                </div>
              </div>
              <div className="tnum" style={{ textAlign: "right", font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{p.deposited}</div>
              <div className="tnum" style={{ textAlign: "right", font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{p.lpTokens}</div>
              <div className="tnum" style={{ textAlign: "right", font: '600 14px/20px "Inter", sans-serif', color: "var(--accent)" }}>{p.apy}</div>
              <div className="tnum" style={{ textAlign: "right", font: '500 14px/20px "Inter", sans-serif', color: "var(--success)" }}>+{p.earnedYield}</div>
              <div className="tnum" style={{ textAlign: "right", font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{p.currentValue}</div>
              <div className="tnum" style={{ textAlign: "right", font: '500 14px/20px "Inter", sans-serif', color: "var(--fg-muted)" }}>{p.withdrawable}</div>
              <div style={{ display: "flex", gap: "var(--space-8)", justifyContent: "flex-end" }}>
                <button className="btn btn--secondary btn--sm" type="button" onClick={() => onDeposit && onDeposit(p)}>Deposit</button>
                <button className="btn btn--secondary btn--sm" type="button" disabled={paused}
                        onClick={() => !paused && onWithdraw && onWithdraw(p)}>Withdraw</button>
              </div>
            </div>
          );
        })}
      </div>

      {positions.length > 0 && (
        <div style={{ padding: "var(--space-8) var(--space-24) var(--space-12)" }}>
          <Pagination
            total={positions.length}
            page={safePage}
            perPage={perPage}
            onPage={setPage}
            onPerPage={setPerPage}
            perPageOptions={[6, 12, 24]}
          />
        </div>
      )}
    </section>
  );
};

// ── Page ────────────────────────────────────────────────────────────────────
const LenderDashboard = ({ data, pools = [], onAction, state = "live", onRetry }) => {
  const [tab, setTab] = React.useState("positions");
  const [flow, setFlow] = React.useState(null);
  const openDeposit = (prefillPosition) => setFlow({ type: "deposit", prefillPosition: null, prefillPool: null });
  const openWithdraw = (prefillPosition) => setFlow({ type: "withdraw", prefillPosition, prefillPool: null });
  const openDepositForPool = (pool) => setFlow({ type: "deposit", prefillPool: pool, prefillPosition: null });
  const openWithdrawForPosition = (pos) => setFlow({ type: "withdraw", prefillPosition: pos, prefillPool: null });

  if (state === "loading") return <PageSkeleton shape="dashboard" />;
  if (state === "error")   return <PageError title="Couldn't load the lender dashboard" body="Lending data is read per-wallet; this might be a transient blip." onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
        <div>
          <Eyebrow>Lend</Eyebrow>
          <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Lender dashboard</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Supply stablecoins to credit facilities and earn yield.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="coins"
            title="No lending positions yet"
            body="Deposit stablecoins into a facility's lending pool to start earning yield. Your positions and reserve coverage will appear here."
            action={{ label: "Deposit stablecoins", icon: "deposit", onClick: openDeposit }}
          />
        </section>
      </div>
    );
  }

  const k = data.kpi;
  const tabs = [
    { value: "positions", label: "Your positions" },
    { value: "reserve",   label: "Reserve & protection" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      {/* Header + quick actions */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: "var(--space-16)", flexWrap: "wrap" }} data-annot-note="C-5 sentence case">
        <div>
          <Eyebrow>Lend</Eyebrow>
          <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Lender dashboard</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 640 }}>
            Supply stablecoins to credit facilities and earn yield. The protocol reserve
            backs your deposits against shortfalls.
          </div>
        </div>
        <div style={{ display: "flex", gap: "var(--space-8)" }}>
          <button className="btn btn--primary" type="button" onClick={openDeposit}>
            <Icon name="deposit" size={14} stroke={1.7}/> Deposit stablecoins
          </button>
          <button className="btn btn--secondary" type="button" onClick={() => openWithdraw(null)}>
            <Icon name="withdraw" size={14} stroke={1.6}/> Withdraw stablecoins
          </button>
        </div>
      </div>

      {/* KPI summary */}
      <section style={{ display: "flex", gap: "var(--space-16)", flexWrap: "wrap" }} data-annot-note="C-4 hero KPI">
        <HeroKPI
          label="Current value"
          value={k.currentValue}
          sub="Deposited principal + earned yield"
          trend={"+" + k.totalEarned + " earned"}
        />
        <div className="kpi-strip" style={{
          flex: "3 1 480px", minWidth: 0,
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: "var(--radius-lg)", display: "flex", flexWrap: "wrap",
        }}>
          <SupportKPI label="Total deposited" value={k.totalDeposited} sub="Principal supplied" />
          <SupportKPI label="Total earned"    value={"+" + k.totalEarned} sub="Yield to date" tone="success" />
          <SupportKPI label="Average APY"     value={k.avgApy} sub="Across positions" />
          <SupportKPI label="Active pools"    value={String(data.positions.length)} sub="Lending positions" last />
        </div>
      </section>

      {/* Subnav */}
      <div role="tablist" aria-label="Lender sections" style={{ display: "flex", gap: "var(--space-4)", flexWrap: "wrap", borderBottom: "1px solid var(--border)" }}>
        {tabs.map((tb) => {
          const active = tab === tb.value;
          return (
            <button key={tb.value} role="tab" aria-selected={active} type="button" onClick={() => setTab(tb.value)} style={{
              all: "unset", cursor: "pointer", padding: "var(--space-12) var(--space-16)", marginBottom: -1,
              font: '500 13px/18px "Inter", sans-serif',
              color: active ? "var(--fg)" : "var(--fg-subtle)",
              borderBottom: `2px solid ${active ? "var(--accent)" : "transparent"}`,
              transition: "color var(--motion-fast), border-color var(--motion-fast)",
            }}>{tb.label}</button>
          );
        })}
      </div>

      {tab === "positions" && (
        <LenderPositionsTable
          positions={data.positions}
          onDeposit={openDepositForPool}
          onWithdraw={openWithdrawForPosition}
        />
      )}
      {tab === "reserve"   && <ReserveProtection reserve={data.reserve} />}

      {flow && (
        <LenderFlowModal
          type={flow.type}
          pools={pools}
          positions={data.positions}
          prefillPool={flow.prefillPool}
          prefillPosition={flow.prefillPosition}
          onClose={() => setFlow(null)}
        />
      )}
    </div>
  );
};

Object.assign(window, { LenderDashboard, LenderPositionsTable, ReserveProtection, LenderFlowModal });
