// Liquidations.jsx — Liquidate → Liquidations (B14).
//
// Fills the last nav stub. Two liquidation paths, per the protocol:
//   · Searchers earn finder's-fee bounties via the DDF (Dutch Discount
//     Facility — a falling-price auction).
//   · Verified buyers liquidate directly per facility once compliance passes.
//
// Three sub-views (tabs): Opportunities (searcher table + DDF), Claim
// settlement (won collateral/proceeds), and History (past liquidations).
// Reuses HeroKPI / SupportKPI (Portfolio.jsx), Pagination (Primitives.jsx),
// and SegmentControl (Portfolio.jsx).

// ── shared: a hero metric + a 3-stat supporting strip ───────────────────────
const LiqKpis = ({ hero, stats }) => (
  <section style={{ display: "flex", gap: "var(--space-16)", flexWrap: "wrap" }} data-annot-note="C-4 hero KPI">
    <HeroKPI label={hero.label} value={hero.value} sub={hero.sub} trend={hero.trend} />
    <div className="kpi-strip" style={{
      flex: "3 1 420px", minWidth: 0,
      background: "var(--surface)", border: "1px solid var(--border)",
      borderRadius: "var(--radius-lg)", display: "flex", flexWrap: "wrap",
    }}>
      {stats.map((s, i) => (
        <SupportKPI key={i} label={s.label} value={s.value} sub={s.sub} tone={s.tone} last={i === stats.length - 1} />
      ))}
    </div>
  </section>
);

// ── shared: paginated table shell ───────────────────────────────────────────
const LiqTable = ({ title, count, cols, head, children }) => (
  <section className="card" style={{ padding: 0 }} data-annot-note="B14 liquidations table">
    <div style={{ padding: "var(--space-20) var(--space-24) var(--space-16)" }}>
      <Eyebrow>Liquidate</Eyebrow>
      <h2 className="section-heading" style={{ marginTop: "var(--space-8)" }}>
        {title}
        <span style={{
          display: "inline-block", marginLeft: "var(--space-12)",
          font: '500 14px/20px "Inter", sans-serif',
          color: "var(--fg-subtle)", verticalAlign: "middle",
        }}>{count}</span>
      </h2>
    </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)",
      }}>
        {head}
      </div>
      {children}
    </div>
  </section>
);

const cellR = { textAlign: "right" };
const tnumCell = (extra) => ({ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)", textAlign: "right", ...extra });

// ── Trigger Liquidation detail + success ────────────────────────────────────
const LiqTriggerDetail = ({ row, onBack }) => {
  const [done, setDone] = React.useState(false);
  const mockTxHash = "0x4f91ab3d77c0e59" + row.account.replace(/[^a-z0-9]/gi, "").slice(0, 8) + "bd9013f8";
  const seizedQty = row.token === "BUIDL" ? "214,500" : row.token === "OUSG" ? "2,960" : row.token === "USYC" ? "119,000" : "96,400";

  if (done) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "var(--space-16)" }}>
          <div style={{
            width: 48, height: 48, borderRadius: "50%",
            background: "var(--green-10)", color: "var(--success)",
            display: "grid", placeItems: "center", flexShrink: 0,
          }}>
            <Icon name="shieldCheck" size={22} stroke={1.5} />
          </div>
          <div>
            <h1 style={{ margin: 0, font: '700 28px/32px "Figtree", sans-serif', letterSpacing: "-0.01em", color: "var(--fg)" }}>
              Liquidation triggered
            </h1>
            <div style={{ font: '400 14px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-4)" }}>
              Transaction submitted. Collateral is being seized and finder's fee allocated.
            </div>
          </div>
        </div>

        <section className="card" style={{ padding: "var(--space-20) var(--space-24)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: "var(--space-16)", columnGap: "var(--space-24)" }}>
            {[
              { label: "Account liquidated", value: row.account, mono: true },
              { label: "Collateral seized", value: seizedQty + " " + row.token },
              { label: "Debt repaid", value: row.debt },
              { label: "Est. finder's fee", value: row.finderFee, color: "var(--success)", bold: true },
            ].map(({ label, value, color, bold, mono }) => (
              <div key={label}>
                <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={mono ? "addr tnum" : "tnum"} style={{
                  font: mono ? '600 13px/18px "JetBrains Mono", monospace' : bold ? '600 14px/20px "Inter", sans-serif' : '500 14px/20px "Inter", sans-serif',
                  color: color || "var(--fg)",
                }}>{value}</div>
              </div>
            ))}
            <div style={{ gridColumn: "1 / -1" }}>
              <div style={{ font: '400 11px/14px "Inter", sans-serif', letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-4)" }}>Transaction</div>
              <MonoAddr full={mockTxHash} />
            </div>
          </div>
        </section>

        <div style={{ display: "flex", gap: "var(--space-12)" }}>
          <button className="btn btn--primary" type="button" onClick={onBack}>
            Back to opportunities
          </button>
          <button className="btn btn--secondary" type="button">
            <Icon name="external" size={13} stroke={1.6} /> View on explorer
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: "var(--space-16)", flexWrap: "wrap", justifyContent: "space-between" }}>
        <div>
          <Eyebrow>Liquidate</Eyebrow>
          <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 28px/32px "Figtree", sans-serif', letterSpacing: "-0.01em", color: "var(--fg)" }}>
            Trigger liquidation
          </h1>
          <div style={{ font: '400 14px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Account <span style={{ font: '600 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{row.account}</span>
          </div>
        </div>
        <button className="btn btn--secondary btn--sm" type="button" onClick={onBack} style={{ marginTop: "var(--space-8)" }}>
          <Icon name="arrow" size={13} stroke={1.6} style={{ transform: "rotate(180deg)" }} /> Back
        </button>
      </div>

      <div style={{ display: "flex", gap: "var(--space-16)", flexWrap: "wrap" }}>
        <HeroKPI label="Collateral value" value={row.collateral} sub={"Token: " + row.token} />
        <div className="kpi-strip" style={{ flex: "3 1 360px", minWidth: 0, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", display: "flex", flexWrap: "wrap" }}>
          <SupportKPI label="Debt to repay" value={row.debt} sub="Outstanding borrow" />
          <SupportKPI label="Health factor" value={row.hf} sub="Below 1.00 — default" tone="danger" />
          <SupportKPI label="Est. finder's fee" value={row.finderFee} sub="Awarded on settlement" tone="success" last />
        </div>
      </div>

      <div style={{ display: "flex", gap: "var(--space-20)", flexWrap: "wrap", alignItems: "flex-start" }}>
        <section className="card" style={{ flex: "2 1 440px", padding: "var(--space-20) var(--space-24)" }}
                 aria-labelledby="liq-trigger-heading">
          <h2 id="liq-trigger-heading" className="section-heading" style={{ marginBottom: "var(--space-16)" }}>Transaction flow</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-12)", marginBottom: "var(--space-24)" }}>
            {[
              "Your wallet calls the DDF liquidation function for this account.",
              "The protocol verifies health factor is below the liquidation threshold.",
              "Collateral is seized and transferred; debt is repaid from the collateral value.",
              "Finder's fee is allocated to your wallet from the seized collateral.",
            ].map((step, i) => (
              <div key={i} style={{ display: "flex", gap: "var(--space-12)", alignItems: "flex-start" }}>
                <div style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: "var(--bg-alt)", border: "1px solid var(--border)",
                  display: "grid", placeItems: "center", flexShrink: 0, marginTop: 1,
                  font: '600 11px/1 "Inter", sans-serif', color: "var(--fg-muted)",
                }}>{i + 1}</div>
                <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{step}</div>
              </div>
            ))}
          </div>
          <button className="btn btn--danger" type="button" style={{ width: "100%" }} onClick={() => setDone(true)}>
            <Icon name="alert" size={14} stroke={1.7} /> Liquidate {row.account}
          </button>
          <div style={{ marginTop: "var(--space-12)", font: 'italic 300 11px/16px "Literata", serif', color: "var(--fg-subtle)", textAlign: "center" }}>
            Direct liquidation is compliance-gated. Transaction evaluated at submission time.
          </div>
        </section>

        <section className="card" style={{ flex: "1 1 260px", padding: "var(--space-20) var(--space-24)" }}
                 aria-labelledby="liq-howit-heading">
          <h2 id="liq-howit-heading" className="section-heading" style={{ marginBottom: "var(--space-16)" }}>How it works</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-12)", marginBottom: "var(--space-20)",
            font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            <p style={{ margin: 0 }}>The DDF (Dutch Discount Facility) is a falling-price auction. When a margin account's health factor drops below 1.00, the collateral becomes available to liquidators at a discount.</p>
            <p style={{ margin: 0 }}>You repay the outstanding debt and receive the collateral plus a finder's fee. The discount starts at 0% and falls until a liquidator takes it.</p>
            <p style={{ margin: 0 }}>Direct liquidators must hold the required compliance claims. Searchers bidding via DDF auction have separate eligibility requirements.</p>
          </div>
          <div style={{ borderTop: "1px solid var(--border)", paddingTop: "var(--space-16)" }}>
            <div style={{ font: '500 11px/14px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-12)" }}>Account details</div>
            {[
              { label: "Borrower", value: row.account, mono: true },
              { label: "Facility", value: row.facility },
              { label: "Collateral token", value: row.token },
              { label: "Health factor", value: row.hf, danger: true },
              { label: "Time in default", value: row.defaultIn },
            ].map(({ label, value, mono, danger }) => (
              <div key={label} style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-8)", marginBottom: "var(--space-8)" }}>
                <span style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-faint)" }}>{label}</span>
                <span className={mono ? "addr tnum" : "tnum"} style={{
                  font: mono ? '500 12px/18px "JetBrains Mono", monospace' : '500 12px/18px "Inter", sans-serif',
                  color: danger ? "var(--danger)" : "var(--fg)",
                  textAlign: "right", maxWidth: "55%",
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                }}>{value}</span>
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

// ── DDF Auctions tab ─────────────────────────────────────────────────────────
const AuctionEligibilityRow = ({ label, met }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "var(--space-12) 0", borderBottom: "1px solid var(--border)" }}>
    <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{label}</span>
    <StatusPill variant={met ? "eligible" : "not-eligible"}>{met ? "Met" : "Required"}</StatusPill>
  </div>
);

const LiqAuctionDetail = ({ auction, verdict, onBack }) => {
  const [bidDone, setBidDone] = React.useState(false);
  const [bidAmt, setBidAmt] = React.useState("");
  const isEligible = verdict === "eligible";

  const eligibilityRows = [
    { label: "KYC verified", met: verdict !== "noIdentity" },
    { label: "ONCHAINID registered", met: verdict !== "noIdentity" },
    { label: "Buyer eligibility claim", met: isEligible },
    { label: "Wallet balance sufficient", met: isEligible },
  ];

  const mockTxHash = "0x7a2c" + auction.id.replace(/[^a-z0-9]/gi, "").slice(0, 10) + "f8a9";

  if (bidDone) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "var(--space-16)" }}>
          <div style={{ width: 48, height: 48, borderRadius: "50%", background: "var(--green-10)", color: "var(--success)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name="shieldCheck" size={22} stroke={1.5} />
          </div>
          <div>
            <h1 style={{ margin: 0, font: '700 28px/32px "Figtree", sans-serif', letterSpacing: "-0.01em", color: "var(--fg)" }}>Bid placed</h1>
            <div style={{ font: '400 14px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-4)" }}>
              Your bid is live. You'll be notified if outbid or if you win the auction.
            </div>
          </div>
        </div>
        <section className="card" style={{ padding: "var(--space-20) var(--space-24)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: "var(--space-16)", columnGap: "var(--space-24)" }}>
            {[
              { label: "Auction", value: auction.id, mono: true },
              { label: "Your bid", value: bidAmt ? "$" + parseFloat(bidAmt.replace(/,/g, "")).toLocaleString() : auction.reservePrice, color: "var(--accent)", bold: true },
              { label: "Collateral", value: auction.collateralQty + " " + auction.token },
              { label: "Reserve price", value: auction.reservePrice },
              { label: "Transaction", value: mockTxHash, mono: true, gridFull: true },
            ].filter(Boolean).map(({ label, value, color, bold, mono, gridFull }) => (
              <div key={label} style={gridFull ? { gridColumn: "1 / -1" } : {}}>
                <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={mono ? "addr tnum" : "tnum"} style={{ font: mono ? '500 12px/18px "JetBrains Mono", monospace' : bold ? '600 14px/20px "Inter", sans-serif' : '500 14px/20px "Inter", sans-serif', color: color || "var(--fg)" }}>{value}</div>
              </div>
            ))}
          </div>
        </section>
        <button className="btn btn--primary" type="button" onClick={onBack}>Back to auctions</button>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: "var(--space-16)", flexWrap: "wrap" }}>
        <div>
          <Eyebrow>DDF auctions</Eyebrow>
          <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 28px/32px "Figtree", sans-serif', letterSpacing: "-0.01em", color: "var(--fg)" }}>
            Auction {auction.id}
          </h1>
          <div style={{ font: '400 14px/20px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            {auction.facility} · {auction.collateralQty} {auction.token}
          </div>
        </div>
        <button className="btn btn--secondary btn--sm" type="button" onClick={onBack} style={{ marginTop: "var(--space-8)" }}>
          <Icon name="arrow" size={13} stroke={1.6} style={{ transform: "rotate(180deg)" }} /> Back
        </button>
      </div>

      <div style={{ display: "flex", gap: "var(--space-16)", flexWrap: "wrap" }}>
        <HeroKPI label="Reserve price" value={auction.reservePrice} sub={"Collateral: " + auction.collateralQty + " " + auction.token} />
        <div className="kpi-strip" style={{ flex: "3 1 360px", minWidth: 0, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", display: "flex", flexWrap: "wrap" }}>
          <SupportKPI label="Current bid" value={auction.currentBid || "No bids yet"} sub={auction.currentBidder ? "From " + auction.currentBidder : "Be the first to bid"} />
          <SupportKPI label="Time remaining" value={auction.timeRemaining} sub="Dutch discount" tone="warning" />
          <SupportKPI label="Health factor" value={auction.healthFactor} sub={"In default " + auction.timeInDefault} tone="danger" last />
        </div>
      </div>

      <div style={{ display: "flex", gap: "var(--space-20)", flexWrap: "wrap", alignItems: "flex-start" }}>
        <div style={{ flex: "2 1 440px", display: "flex", flexDirection: "column", gap: "var(--space-16)" }}>
          <section className="card" style={{ padding: "var(--space-20) var(--space-24)" }} aria-labelledby="auction-elig-heading">
            <h2 id="auction-elig-heading" className="section-heading" style={{ marginBottom: "var(--space-4)" }}>Eligibility check</h2>
            <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-16)" }}>
              All requirements must be met to bid on this auction. Status reflects the current compliance scenario.
            </div>
            {eligibilityRows.map((r) => <AuctionEligibilityRow key={r.label} {...r} />)}
            {isEligible ? (
              <div style={{
                marginTop: "var(--space-16)", padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)",
                background: "var(--green-10)", display: "flex", gap: "var(--space-8)", alignItems: "center",
                font: '500 13px/18px "Inter", sans-serif', color: "var(--success)",
              }}>
                <Icon name="shieldCheck" size={14} stroke={1.7} /> Eligible to bid on this auction
              </div>
            ) : (
              <div style={{
                marginTop: "var(--space-16)", padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)",
                background: "var(--red-10)", display: "flex", gap: "var(--space-8)", alignItems: "center",
                font: '400 13px/18px "Inter", sans-serif', color: "var(--danger)",
              }}>
                <Icon name="alert" size={14} stroke={1.7} /> One or more eligibility requirements are not met. Resolve via the Facility access page.
              </div>
            )}
          </section>

          <section className="card" style={{ padding: "var(--space-20) var(--space-24)" }} aria-labelledby="auction-bid-heading">
            <h2 id="auction-bid-heading" className="section-heading" style={{ marginBottom: "var(--space-16)" }}>Place a bid</h2>
            <label style={{ display: "block", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginBottom: "var(--space-8)" }}>
              Bid amount (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)", marginBottom: "var(--space-16)" }}>
              <input
                value={bidAmt}
                onChange={(e) => setBidAmt(e.target.value)}
                inputMode="decimal"
                placeholder="0.00"
                disabled={!isEligible}
                style={{ flex: 1, border: 0, outline: 0, font: '500 20px/28px "Figtree", sans-serif', color: "var(--fg)", background: "transparent", padding: "var(--space-12) 0", fontVariantNumeric: "tabular-nums", opacity: isEligible ? 1 : 0.4 }}
              />
              <span className="chip chip--neutral" style={{ padding: "var(--space-4) var(--space-8)" }}>USDC</span>
              <button className="btn btn--ghost btn--sm" type="button" disabled={!isEligible} onClick={() => setBidAmt(auction.reservePrice.replace("$", "").replace(/,/g, ""))}>MAX</button>
            </div>
            <div style={{ display: "flex", gap: "var(--space-12)" }}>
              <button className="btn btn--primary" type="button" disabled={!isEligible} style={{ flex: 1 }} onClick={() => isEligible && setBidDone(true)}>
                Review bid
                <Icon name="arrow" size={13} stroke={1.6} />
              </button>
              <button className="btn btn--secondary" type="button" disabled={!isEligible} onClick={() => isEligible && setBidDone(true)}>
                Buy at reserve ({auction.reservePrice})
              </button>
            </div>
            {!isEligible && (
              <div style={{ marginTop: "var(--space-12)", font: 'italic 300 11px/16px "Literata", serif', color: "var(--fg-subtle)", textAlign: "center" }}>
                Resolve eligibility requirements above to enable bidding.
              </div>
            )}
          </section>
        </div>

        <section className="card" style={{ flex: "1 1 260px", padding: "var(--space-20) var(--space-24)" }} aria-labelledby="auction-info-heading">
          <h2 id="auction-info-heading" className="section-heading" style={{ marginBottom: "var(--space-16)" }}>Auction details</h2>
          {[
            { label: "Account", value: auction.account, mono: true },
            { label: "Facility", value: auction.facility },
            { label: "Collateral", value: auction.collateralQty + " " + auction.token },
            { label: "Reserve price", value: auction.reservePrice },
            { label: "Started", value: auction.startedAt },
            { label: "Time in default", value: auction.timeInDefault },
          ].map(({ label, value, mono }) => (
            <div key={label} style={{ display: "flex", justifyContent: "space-between", gap: "var(--space-8)", marginBottom: "var(--space-12)" }}>
              <span style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-faint)" }}>{label}</span>
              <span className={mono ? "addr tnum" : ""} style={{
                font: mono ? '500 12px/18px "JetBrains Mono", monospace' : '500 12px/18px "Inter", sans-serif',
                color: "var(--fg)", textAlign: "right", maxWidth: "55%",
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
              }}>{value}</span>
            </div>
          ))}
          <div style={{ marginTop: "var(--space-12)", borderTop: "1px solid var(--border)", paddingTop: "var(--space-16)" }}>
            <div style={{ font: '500 11px/14px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-faint)", marginBottom: "var(--space-12)" }}>Settlement conditions</div>
            <div style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
              Winning bidder repays the outstanding debt and receives the {auction.token} collateral. Settlement is atomic — both legs execute in the same transaction or neither does.
            </div>
          </div>
        </section>
      </div>
    </div>
  );
};

const LiqDdfAuctions = ({ auctions, verdict, onOpenAuction }) => {
  const cols = "minmax(140px, 1.2fr) 1fr 1fr 1fr 1fr auto";
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <LiqKpis
        hero={{ label: "Live auctions", value: String(auctions.length), sub: "Dutch Discount Facility · falling-price" }}
        stats={[
          { label: "Total collateral", value: auctions.reduce((s, a) => s, "$742,600"), sub: "Across live auctions" },
          { label: "Lowest reserve", value: "$90,100", sub: "Starting from" },
          { label: "Active bidders", value: String(auctions.filter(a => a.currentBid).length), sub: "Have at least one bid" },
        ]}
      />

      <div style={{ padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)", background: "var(--bg-alt)", font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", display: "flex", gap: "var(--space-12)", alignItems: "flex-start" }}>
        <Icon name="info" size={15} stroke={1.7} style={{ flexShrink: 0, marginTop: "var(--space-2)", color: "var(--fg-muted)" }} />
        <span>DDF auctions are compliance-gated. You must hold the required eligibility claims to bid. The price starts at the reserve and falls over time — earlier bids carry less discount but more certainty of winning.</span>
      </div>

      <section className="card" style={{ padding: 0 }}>
        <div style={{ padding: "var(--space-20) var(--space-24) var(--space-16)" }}>
          <Eyebrow>Liquidate</Eyebrow>
          <h2 className="section-heading" style={{ marginTop: "var(--space-8)" }}>
            Live auctions
            <span style={{ display: "inline-block", marginLeft: "var(--space-12)", font: '500 14px/20px "Inter", sans-serif', color: "var(--fg-subtle)", verticalAlign: "middle" }}>{auctions.length}</span>
          </h2>
        </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>Account</span>
            <span style={cellR}>Collateral</span>
            <span style={cellR}>Reserve</span>
            <span style={cellR}>Current bid</span>
            <span style={cellR}>Time left</span>
            <span></span>
          </div>
          {auctions.map((a, i) => (
            <div key={a.id} 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)" }}>
                  <span className="addr" style={{ font: '600 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{a.account}</span>
                  <span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{a.token}</span>
                </div>
                <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-2)" }}>{a.facility}</div>
              </div>
              <div className="tnum" style={tnumCell()}>{a.collateralValue}</div>
              <div className="tnum" style={tnumCell({ color: "var(--fg-muted)" })}>{a.reservePrice}</div>
              <div className="tnum" style={tnumCell({ color: a.currentBid ? "var(--fg)" : "var(--fg-faint)" })}>{a.currentBid || "—"}</div>
              <div className="tnum" style={{ textAlign: "right", font: '500 12px/16px "Inter", sans-serif', color: parseInt(a.timeRemaining) < 20 ? "var(--danger)" : "var(--gold-70)" }}>{a.timeRemaining}</div>
              <div style={{ textAlign: "right" }}>
                <button className="btn btn--secondary btn--sm" type="button" onClick={() => onOpenAuction && onOpenAuction(a)}>Place bid</button>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

// ── Opportunities (searcher table + DDF) ────────────────────────────────────
const LiqOpportunities = ({ data, onLiquidate }) => {
  const [token, setToken] = React.useState("all");
  const [page, setPage] = React.useState(1);
  const [perPage, setPerPage] = React.useState(6);
  React.useEffect(() => { setPage(1); }, [token]);

  const k = data.kpi;
  const tokens = ["BUIDL", "USYC", "STBT", "OUSG"];
  const filtered = data.rows.filter((r) => token === "all" ? true : r.token === token);
  const pageCount = Math.max(1, Math.ceil(filtered.length / perPage));
  const safePage = Math.min(page, pageCount);
  const rows = filtered.slice((safePage - 1) * perPage, safePage * perPage);
  const cols = "minmax(150px, 1.4fr) 1fr 1fr 0.6fr 0.8fr 1fr auto";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <LiqKpis
        hero={{ label: "Potential bounties", value: k.potentialBounties, sub: `Finder's fees across ${k.positions} liquidatable positions` }}
        stats={[
          { label: "Positions at risk", value: k.positions, sub: `${k.profitable} profitable to liquidate`, tone: "danger" },
          { label: "Total collateral value", value: k.collateralValue, sub: "Across opportunities" },
          { label: "DDF auctions live", value: k.ddfAuctions, sub: "Falling-price auctions" },
        ]}
      />

      {/* DDF framing */}
      <div style={{
        display: "flex", alignItems: "flex-start", gap: "var(--space-12)",
        padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)",
        background: "var(--bg-alt)",
        font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)",
      }} data-annot-note="B14 DDF framing">
        <Icon name="info" size={15} stroke={1.7} style={{ flexShrink: 0, marginTop: "var(--space-2)", color: "var(--fg-muted)" }}/>
        <span>
          Searchers earn the finder's fee via the <span style={{ color: "var(--fg-muted)", fontWeight: 500 }}>DDF</span> (Dutch Discount
          Facility, a falling-price auction). Verified buyers may liquidate directly per facility once compliance passes.
        </span>
      </div>

      {/* Token filter */}
      <div>
        <SegmentControl
          value={token}
          onChange={setToken}
          options={[
            { value: "all", label: "All tokens", count: data.rows.length },
            ...tokens.map((t) => ({ value: t, label: t, count: data.rows.filter((r) => r.token === t).length })),
          ]}
        />
      </div>

      <LiqTable
        title="Liquidation opportunities" count={filtered.length} cols={cols}
        head={<>
          <span>Account</span>
          <span style={cellR}>Collateral</span>
          <span style={cellR}>Debt</span>
          <span style={cellR}>HF</span>
          <span style={cellR}>Default</span>
          <span style={cellR}>Finder's fee</span>
          <span></span>
        </>}
      >
        {rows.map((r, i) => (
          <div key={r.account} 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 className="addr" style={{ font: '600 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{r.account}</span>
                <span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{r.token}</span>
              </div>
              <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-2)" }}>{r.facility}</div>
            </div>
            <div className="tnum" style={tnumCell()}>{r.collateral}</div>
            <div className="tnum" style={tnumCell({ color: "var(--fg-muted)" })}>{r.debt}</div>
            <div className="tnum" style={tnumCell({ color: "var(--danger)", fontWeight: 600 })}>{r.hf}</div>
            <div className="tnum" style={{ textAlign: "right", font: '400 12px/16px "Inter", sans-serif', color: r.defaultIn === "Now" ? "var(--danger)" : "var(--gold-70)" }}>{r.defaultIn}</div>
            <div className="tnum" style={tnumCell({ color: "var(--success)", fontWeight: 600 })}>{r.finderFee}</div>
            <div style={{ textAlign: "right" }}>
              <button className="btn btn--secondary btn--sm" type="button" onClick={() => onLiquidate && onLiquidate(r)}>Liquidate</button>
            </div>
          </div>
        ))}
      </LiqTable>

      {filtered.length > 0 && (
        <Pagination total={filtered.length} page={safePage} perPage={perPage} onPage={setPage} onPerPage={setPerPage} perPageOptions={[6, 12, 24]} />
      )}
    </div>
  );
};

// ── Claim settlement ────────────────────────────────────────────────────────
const SETTLE_STATUS = {
  claimable: { variant: "eligible",     label: "Claimable" },
  expiring:  { variant: "at-risk",      label: "Expiring soon" },
  expired:   { variant: "frozen",       label: "Expired" },
};

const LiqSettlements = ({ data, onAction }) => {
  const [filter, setFilter] = React.useState("all");
  const [page, setPage] = React.useState(1);
  const [perPage, setPerPage] = React.useState(6);
  React.useEffect(() => { setPage(1); }, [filter]);

  const k = data.kpi;
  const filtered = data.rows.filter((r) =>
    filter === "all" ? true :
    filter === "expiring" ? r.status === "expiring" :
    filter === "expired" ? r.status === "expired" :
    filter === "claimable" ? r.status === "claimable" : true
  );
  const pageCount = Math.max(1, Math.ceil(filtered.length / perPage));
  const safePage = Math.min(page, pageCount);
  const rows = filtered.slice((safePage - 1) * perPage, safePage * perPage);
  const cols = "minmax(120px, 1.2fr) 0.7fr 1fr 1fr 1fr 0.9fr auto";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <LiqKpis
        hero={{ label: "Total claimable", value: k.totalValue, sub: `Across ${k.claimable} settlements ready to claim` }}
        stats={[
          { label: "Claimable settlements", value: k.claimable, sub: "Won at auction or direct", tone: "success" },
          { label: "Claimed this month", value: k.claimedThisMonth, sub: "Pulled to wallet" },
          { label: "Expiring soon", value: k.expiringSoon, sub: "Claim before deadline", tone: "warning" },
        ]}
      />

      <div style={{
        display: "flex", alignItems: "flex-start", gap: "var(--space-12)",
        padding: "var(--space-12) var(--space-16)", borderRadius: "var(--radius-md)", background: "var(--bg-alt)",
        font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)",
      }}>
        <Icon name="shieldCheck" size={15} stroke={1.7} style={{ flexShrink: 0, marginTop: "var(--space-2)", color: "var(--fg-muted)" }}/>
        <span>For verified buyers only: pull collateral or proceeds after you won a DDF auction or directly liquidated a position.</span>
      </div>

      <div>
        <SegmentControl
          value={filter}
          onChange={setFilter}
          options={[
            { value: "all",       label: "All",          count: data.rows.length },
            { value: "claimable", label: "Claimable",    count: data.rows.filter((r) => r.status === "claimable").length },
            { value: "expiring",  label: "Expiring soon", count: data.rows.filter((r) => r.status === "expiring").length },
            { value: "expired",   label: "Expired",      count: data.rows.filter((r) => r.status === "expired").length },
          ]}
        />
      </div>

      <LiqTable
        title="Claim settlements" count={filtered.length} cols={cols}
        head={<>
          <span>Account</span>
          <span>Token</span>
          <span style={cellR}>Amount</span>
          <span style={cellR}>Est. value</span>
          <span style={cellR}>Deadline</span>
          <span style={cellR}>Status</span>
          <span></span>
        </>}
      >
        {rows.map((r, i) => {
          const st = SETTLE_STATUS[r.status] || SETTLE_STATUS.claimable;
          const expired = r.status === "expired";
          return (
            <div key={r.account} 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",
            }}>
              <span className="addr" style={{ font: '600 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{r.account}</span>
              <span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11, justifySelf: "start" }}>{r.token}</span>
              <div className="tnum" style={tnumCell()}>{r.amount}</div>
              <div className="tnum" style={tnumCell({ color: "var(--fg-muted)" })}>{r.estValue}</div>
              <div className="tnum" style={{ textAlign: "right", font: '400 13px/20px "Inter", sans-serif', color: r.status === "expiring" ? "var(--gold-70)" : "var(--fg-subtle)" }}>{r.deadline}</div>
              <div style={{ textAlign: "right" }}><StatusPill variant={st.variant}>{st.label}</StatusPill></div>
              <div style={{ textAlign: "right" }}>
                <button className="btn btn--secondary btn--sm" type="button" disabled={expired}
                        onClick={() => !expired && onAction && onAction("Claim " + r.account)}>Claim</button>
              </div>
            </div>
          );
        })}
      </LiqTable>

      {filtered.length > 0 && (
        <Pagination total={filtered.length} page={safePage} perPage={perPage} onPage={setPage} onPerPage={setPerPage} perPageOptions={[6, 12, 24]} />
      )}
    </div>
  );
};

// ── History ─────────────────────────────────────────────────────────────────
const LiqHistory = ({ data }) => {
  const [page, setPage] = React.useState(1);
  const [perPage, setPerPage] = React.useState(6);
  const k = data.kpi;
  const pageCount = Math.max(1, Math.ceil(data.rows.length / perPage));
  const safePage = Math.min(page, pageCount);
  const rows = data.rows.slice((safePage - 1) * perPage, safePage * perPage);
  const cols = "0.9fr minmax(110px, 1fr) 1fr 1fr 0.9fr 0.9fr auto";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <LiqKpis
        hero={{ label: "Net profit / loss", value: k.netPnl, sub: `Across ${k.totalLiquidations} completed liquidations`, trend: k.netPnl }}
        stats={[
          { label: "Total liquidations", value: k.totalLiquidations, sub: "Completed" },
          { label: "Debt repaid", value: k.debtRepaid, sub: "Across positions" },
          { label: "Collateral acquired", value: k.collateralAcquired, sub: "Pulled to wallet" },
        ]}
      />

      <LiqTable
        title="Liquidation history" count={data.rows.length} cols={cols}
        head={<>
          <span>Date</span>
          <span>Account</span>
          <span style={cellR}>Collateral</span>
          <span style={cellR}>Debt repaid</span>
          <span style={cellR}>P&amp;L</span>
          <span style={cellR}>Status</span>
          <span></span>
        </>}
      >
        {rows.map((r, i) => (
          <div key={r.hash} 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={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-muted)" }}>{r.date}</div>
            <span className="addr" style={{ font: '600 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{r.account}</span>
            <div className="tnum" style={tnumCell()}>{r.qty} <span style={{ color: "var(--fg-subtle)", fontWeight: 400 }}>{r.token}</span></div>
            <div className="tnum" style={tnumCell({ color: "var(--fg-muted)" })}>{r.debtRepaid}</div>
            <div className="tnum" style={tnumCell({ color: "var(--success)", fontWeight: 600 })}>{r.pnl}</div>
            <div style={{ textAlign: "right" }}><StatusPill variant="executed">Claimed</StatusPill></div>
            <div style={{ textAlign: "right" }}>
              <span className="btn btn--text" style={{ fontSize: 12 }}>Tx <Icon name="external" size={11} stroke={1.6}/></span>
            </div>
          </div>
        ))}
      </LiqTable>

      {data.rows.length > 0 && (
        <Pagination total={data.rows.length} page={safePage} perPage={perPage} onPage={setPage} onPerPage={setPerPage} perPageOptions={[6, 12, 24]} />
      )}
    </div>
  );
};

// ── Page ────────────────────────────────────────────────────────────────────
const Liquidations = ({
  data, auctions = [], onLiquidate, onAction,
  openedLiquidation, onClearLiquidation,
  openedAuction, onOpenAuction, onClearAuction,
  verdict = "eligible",
  state = "live", onRetry,
}) => {
  const [tab, setTab] = React.useState("opportunities");

  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load liquidations" body="Liquidation data is read from the indexer; this might be a transient delay." onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
        <div>
          <Eyebrow>Liquidate</Eyebrow>
          <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Liquidations</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Liquidate distressed positions and claim the collateral.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState icon="alert" title="No liquidation opportunities" body="When a margin account's health factor falls below its threshold it appears here for searchers and verified buyers." />
        </section>
      </div>
    );
  }

  // Trigger detail — render instead of the tab view
  if (openedLiquidation) {
    return <LiqTriggerDetail row={openedLiquidation} onBack={onClearLiquidation} />;
  }

  // Auction detail — render instead of the tab view
  if (openedAuction) {
    return <LiqAuctionDetail auction={openedAuction} verdict={verdict} onBack={onClearAuction} />;
  }

  const tabs = [
    { value: "opportunities", label: "Opportunities" },
    { value: "auctions",      label: "DDF auctions" },
    { value: "settlement",    label: "Claim settlement" },
    { value: "history",       label: "History" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      {/* Header */}
      <div data-annot-note="C-5 sentence case">
        <Eyebrow>Liquidate</Eyebrow>
        <h1 style={{ margin: "var(--space-8) 0 var(--space-8)", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Liquidations</h1>
        <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)", maxWidth: 680 }}>
          Searchers earn bounties via the DDF; verified buyers liquidate directly per facility when compliance passes.
        </div>
      </div>

      {/* Subnav */}
      <div role="tablist" aria-label="Liquidation 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 === "opportunities" && <LiqOpportunities data={data.opportunities} onLiquidate={onLiquidate} />}
      {tab === "auctions"      && <LiqDdfAuctions auctions={auctions} verdict={verdict} onOpenAuction={onOpenAuction} />}
      {tab === "settlement"    && <LiqSettlements data={data.settlements} onAction={onAction} />}
      {tab === "history"       && <LiqHistory data={data.history} />}
    </div>
  );
};

Object.assign(window, { Liquidations, LiqOpportunities, LiqSettlements, LiqHistory, LiqTriggerDetail, LiqDdfAuctions, LiqAuctionDetail });
