/* ─────────────────────────────────────────────────────
   Equipment Balkans — Buyer trust & payments
   Card on file · pre-authorization holds · escrow checkout · wire transfer
───────────────────────────────────────────────────── */
const { useState: usePay, useEffect: usePayE } = React;

const HIGH_VALUE_THRESHOLD = 500; // lots >= this need a pre-auth hold
const BUYER_PREMIUM = 0.05;        // 5% buyer's premium at checkout
const preauthFor = (lotValue) => Math.round((Number(lotValue) || 0) * 0.10);

function cardBrand(num) {
  const n = String(num).replace(/\s/g, "");
  if (/^4/.test(n)) return "Visa";
  if (/^5[1-5]/.test(n)) return "Mastercard";
  if (/^3[47]/.test(n)) return "Amex";
  return "Card";
}

// ── Modal shell ─────────────────────────────────────
function Modal({ children, onClose, width = 460 }) {
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 150, background: "rgba(8,12,22,0.62)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: width, background: "var(--surface)", border: "1px solid var(--border-s)", borderRadius: 16, boxShadow: "0 24px 60px rgba(0,0,0,0.5)", maxHeight: "92vh", overflowY: "auto" }}>
        {children}
      </div>
    </div>
  );
}
function ModalHead({ icon, title, sub, onClose, accent = "var(--ignite)" }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 13, padding: "22px 22px 0" }}>
      <span style={{ width: 42, height: 42, borderRadius: 11, background: "color-mix(in srgb," + "var(--ignite) 12%, transparent)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, backgroundColor: "rgba(249,115,22,0.12)" }}>
        <i data-lucide={icon} style={{ width: 20, height: 20, color: accent }}></i>
      </span>
      <div style={{ flex: 1 }}>
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 21, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", margin: 0, lineHeight: 1.1 }}>{title}</h2>
        {sub && <p style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 4, lineHeight: 1.5 }}>{sub}</p>}
      </div>
      <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 7, color: "var(--text-3)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <i data-lucide="x" style={{ width: 17, height: 17 }}></i>
      </button>
    </div>
  );
}

// ── Add card modal ──────────────────────────────────
function AddCardModal({ onClose, onSave }) {
  const [num, setNum] = usePay("");
  const [name, setName] = usePay("");
  const [exp, setExp] = usePay("");
  const [cvc, setCvc] = usePay("");
  const [country, setCountry] = usePay("Serbia");
  const [err, setErr] = usePay("");

  const fmtNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const fmtExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length > 2 ? d.slice(0, 2) + "/" + d.slice(2) : d; };

  const save = () => {
    const digits = num.replace(/\s/g, "");
    if (digits.length < 15) return setErr("Enter a valid card number.");
    if (!name) return setErr("Enter the cardholder name.");
    if (exp.length < 5) return setErr("Enter the expiry date.");
    if (cvc.length < 3) return setErr("Enter the CVC.");
    onSave({ brand: cardBrand(digits), last4: digits.slice(-4), exp, name, country });
  };

  return (
    <Modal onClose={onClose}>
      <ModalHead icon="credit-card" title="Add a payment method" sub="Securely store a card to bid, pre-authorize holds and check out. We never charge it without your action." onClose={onClose} />
      <div style={{ padding: "18px 22px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
        {err && <div style={payErr}><i data-lucide="alert-triangle" style={{ width: 14, height: 14, color: "#F87171" }}></i>{err}</div>}
        <PayField label="Card number">
          <div style={{ position: "relative" }}>
            <input value={num} onChange={(e) => setNum(fmtNum(e.target.value))} placeholder="4242 4242 4242 4242" style={{ ...inputStyle, fontFamily: "var(--ff-mono)", letterSpacing: ".04em" }} />
            <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", fontSize: 11, fontWeight: 700, color: "var(--text-3)" }}>{num ? cardBrand(num) : ""}</span>
          </div>
        </PayField>
        <PayField label="Cardholder name"><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Marko Petrović" style={inputStyle} /></PayField>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <PayField label="Expiry"><input value={exp} onChange={(e) => setExp(fmtExp(e.target.value))} placeholder="MM/YY" style={{ ...inputStyle, fontFamily: "var(--ff-mono)" }} /></PayField>
          <PayField label="CVC"><input value={cvc} onChange={(e) => setCvc(e.target.value.replace(/\D/g, "").slice(0, 4))} placeholder="123" style={{ ...inputStyle, fontFamily: "var(--ff-mono)" }} /></PayField>
        </div>
        <PayField label="Billing country">
          <select value={country} onChange={(e) => setCountry(e.target.value)} style={{ ...inputStyle, cursor: "pointer" }}>
            {["Serbia", "Croatia", "Slovenia", "Bosnia & Herzegovina", "Montenegro", "North Macedonia", "Albania", "Other (EU)"].map((c) => <option key={c}>{c}</option>)}
          </select>
        </PayField>
        <div style={lockNote}><i data-lucide="lock" style={{ width: 12, height: 12 }}></i> Encrypted &amp; tokenized. PCI-DSS compliant.</div>
        <button onClick={save} style={{ ...primaryBtn, width: "100%", justifyContent: "center", padding: "13px", fontSize: 14 }}>Save card</button>
      </div>
    </Modal>
  );
}

// ── Pre-authorization modal ─────────────────────────
function PreauthModal({ auction, wallet, onClose, onAuthorize }) {
  const lotValue = Number(auction.startingPrice) || 0;
  const hold = preauthFor(lotValue);
  return (
    <Modal onClose={onClose}>
      <ModalHead icon="shield-check" title="Pre-authorize to bid" sub="This is a higher-value lot, so we place a small refundable hold before you can bid." onClose={onClose} accent="var(--cobalt)" />
      <div style={{ padding: "18px 22px 22px", display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center", background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 10, padding: 12 }}>
          <EquipImage src={auction.images[0]} alt="" style={{ width: 56, height: 44, borderRadius: 6, objectFit: "cover", flexShrink: 0 }} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{auction.title}</div>
            <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Estimated minimum {eur(lotValue)}</div>
          </div>
        </div>

        <div style={{ background: "rgba(37,99,235,0.07)", border: "1px solid rgba(37,99,235,0.22)", borderRadius: 10, padding: "16px 18px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em", color: "var(--cobalt)" }}>Refundable hold (10%)</span>
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 26, fontWeight: 700, color: "var(--text)" }}>{eur(hold)}</span>
          </div>
        </div>

        <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 9, margin: 0 }}>
          {[
            ["lock", "We place a hold — not a charge — on your card."],
            ["undo-2", "Released automatically the moment the auction ends if you don't win."],
            ["gavel", "Win, and the hold is applied toward your 24-hour payment."],
          ].map(([ic, t]) => (
            <li key={t} style={{ display: "flex", gap: 9, fontSize: 12.5, color: "var(--text-2)", alignItems: "flex-start" }}>
              <i data-lucide={ic} style={{ width: 15, height: 15, color: "var(--cobalt)", flexShrink: 0, marginTop: 1 }}></i><span>{t}</span>
            </li>
          ))}
        </ul>

        {wallet.card && (
          <div style={cardRow}>
            <i data-lucide="credit-card" style={{ width: 16, height: 16, color: "var(--text-2)" }}></i>
            <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{wallet.card.brand} •••• {wallet.card.last4}</span>
          </div>
        )}

        <button onClick={() => onAuthorize(auction.id, hold)} style={{ ...primaryBtn, width: "100%", justifyContent: "center", padding: "13px", fontSize: 14, background: "var(--cobalt)" }}>
          <i data-lucide="shield-check" style={{ width: 16, height: 16 }}></i> Authorize {eur(hold)} hold
        </button>
      </div>
    </Modal>
  );
}

// ── Bid gate (shown in the detail bid panel) ────────
function BidGate({ auction, wallet, onAddCard, onPreauth }) {
  const lotValue = Number(auction.startingPrice) || 0;
  const needsPreauth = lotValue >= HIGH_VALUE_THRESHOLD;
  const hasCard = !!(wallet && wallet.card);
  const hold = preauthFor(lotValue);

  if (!hasCard) {
    return (
      <div style={{ ...panelCard, textAlign: "center" }}>
        <span style={gateIcon("var(--ignite)")}><i data-lucide="credit-card" style={{ width: 20, height: 20, color: "var(--ignite)" }}></i></span>
        <div style={gateTitle}>Add a card to bid</div>
        <div style={gateSub}>
          {needsPreauth
            ? "Save a card to continue. This lot is over €500, so we'll place a small refundable hold before bidding."
            : "Lots under €500 only need a card on file — no deposit required."}
        </div>
        <button onClick={onAddCard} style={{ ...primaryBtn, width: "100%", justifyContent: "center" }}><i data-lucide="plus" style={{ width: 15, height: 15 }}></i> Add a payment method</button>
        <div style={{ ...lockNote, justifyContent: "center", marginTop: 11 }}><i data-lucide="shield" style={{ width: 12, height: 12 }}></i> You're never charged just to bid.</div>
      </div>
    );
  }
  // has card, needs pre-auth
  return (
    <div style={{ ...panelCard, textAlign: "center" }}>
      <span style={gateIcon("var(--cobalt)")}><i data-lucide="shield-check" style={{ width: 20, height: 20, color: "var(--cobalt)" }}></i></span>
      <div style={gateTitle}>Pre-authorize to bid</div>
      <div style={gateSub}>This lot is over €500. We'll place a refundable <strong style={{ color: "var(--text)" }}>{eur(hold)}</strong> hold (10% of the estimated minimum) — released if you don't win.</div>
      <div style={{ ...cardRow, justifyContent: "center", marginBottom: 12 }}>
        <i data-lucide="credit-card" style={{ width: 15, height: 15, color: "var(--text-3)" }}></i>
        <span style={{ fontSize: 12, color: "var(--text-3)" }}>{wallet.card.brand} •••• {wallet.card.last4}</span>
      </div>
      <button onClick={() => onPreauth(auction)} style={{ ...primaryBtn, width: "100%", justifyContent: "center", background: "var(--cobalt)" }}>
        <i data-lucide="shield-check" style={{ width: 15, height: 15 }}></i> Authorize {eur(hold)} &amp; bid
      </button>
    </div>
  );
}

// ── Escrow status timeline ──────────────────────────
function EscrowTimeline({ status, method }) {
  const steps = [
    { key: "paid", label: method === "wire" ? "Wire received" : "Payment captured", icon: "check" },
    { key: "escrow", label: "Held in escrow", icon: "shield" },
    { key: "delivered", label: "Delivered & inspected", icon: "truck" },
    { key: "released", label: "Funds released to seller", icon: "check-circle-2" },
  ];
  const order = { awaiting_wire: 0, in_escrow: 1, delivered: 2, released: 3 };
  const cur = order[status] ?? 1;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
      {steps.map((s, i) => {
        const done = i < cur;
        const active = i === cur;
        const on = done || active;
        return (
          <div key={s.key} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
              <span style={{ width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, background: done ? "#22C55E" : active ? "var(--ignite)" : "var(--surface-2)", color: on ? "#fff" : "var(--text-3)" }}>
                <i data-lucide={done ? "check" : s.icon} style={{ width: 14, height: 14 }}></i>
              </span>
              {i < steps.length - 1 && <span style={{ width: 2, height: 22, background: done ? "#22C55E" : "var(--border)" }}></span>}
            </div>
            <div style={{ paddingTop: 4, paddingBottom: 14 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: on ? "var(--text)" : "var(--text-3)" }}>{s.label}</div>
              {active && <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 1 }}>In progress</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── Checkout screen (won auction or marketplace buy) ─
function CheckoutScreen({ store, route, wallet, user, onNav, onPay, onAddCard }) {
  const item = store.auctions.find((a) => a.id === route.id);
  const [method, setMethod] = usePay("card");
  const [warranty, setWarranty] = usePay("none");
  const [transport, setTransport] = usePay(false);
  const mode = route.mode || "won"; // 'won' | 'buy'

  if (!item) {
    return <div style={{ maxWidth: 700, margin: "0 auto", padding: "80px 24px", textAlign: "center", color: "var(--text-3)" }}>Item not found. <button onClick={() => onNav({ name: "auctions" })} style={{ color: "var(--cobalt)", fontWeight: 700 }}>Back to auctions</button></div>;
  }

  const escrow = (wallet.escrow || []).find((e) => e.refId === item.id);
  const winBid = store.userBids[item.id]?.amount;
  const baseAmount = mode === "buy" ? Number(item.askingPrice) : Number(winBid || item.currentBid || item.startingPrice);
  const premium = Math.round(baseAmount * BUYER_PREMIUM);
  const svcMeta = window.EB_SERVICES_META || { INSPECTION_THRESHOLD: 25000, WARRANTY: { oneYearRate: 0.04, twoYearRate: 0.07 } };
  const inspectable = baseAmount >= svcMeta.INSPECTION_THRESHOLD;
  const wr = svcMeta.WARRANTY || { oneYearRate: 0.04, twoYearRate: 0.07 };
  const warrantyCost = !inspectable ? 0 : warranty === "1y" ? Math.round(baseAmount * wr.oneYearRate) : warranty === "2y" ? Math.round(baseAmount * wr.twoYearRate) : 0;
  const transportCost = transport ? Math.round(baseAmount * 0.015) + 450 : 0;
  const total = baseAmount + premium + warrantyCost + transportCost;
  const wonAt = store.userBids[item.id]?.won?.at;
  const dueAt = wonAt ? wonAt + 24 * 3600 * 1000 : null;

  // Already paid → show escrow status
  if (escrow) {
    return (
      <div style={{ maxWidth: 640, margin: "0 auto", padding: "30px 24px 60px" }}>
        <button onClick={() => onNav({ name: "account", tab: "payments" })} style={backLink}><i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Payments</button>
        <div style={{ textAlign: "center", marginBottom: 26 }}>
          <span style={{ width: 60, height: 60, borderRadius: 15, background: "rgba(34,197,94,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
            <i data-lucide="shield-check" style={{ width: 28, height: 28, color: "#22C55E" }}></i>
          </span>
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 30, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0 }}>
            {escrow.method === "wire" && escrow.status === "awaiting_wire" ? "Wire transfer pending" : "Funds in escrow"}
          </h1>
          <p style={{ fontSize: 14, color: "var(--text-2)", marginTop: 10, lineHeight: 1.6 }}>
            {eur(escrow.amount)} for <strong style={{ color: "var(--text)" }}>{item.title}</strong> is protected. The seller is paid only once you confirm delivery.
          </p>
        </div>
        <div style={{ ...panelCard, padding: 22 }}>
          <EscrowTimeline status={escrow.status} method={escrow.method} />
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
          <button onClick={() => onNav({ name: "account", tab: "payments" })} style={{ ...primaryBtn, flex: 1, justifyContent: "center" }}>Track in Payments</button>
          <button onClick={() => onNav({ name: "auctions" })} style={{ ...ghostBtn, flex: 1, justifyContent: "center" }}>Keep browsing</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 920, margin: "0 auto", padding: "26px 24px 60px" }}>
      <button onClick={() => onNav(mode === "buy" ? { name: "detail", id: item.id } : { name: "account", tab: "bids" })} style={backLink}>
        <i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Back
      </button>

      {mode === "won" && (
        <div style={{ display: "flex", alignItems: "center", gap: 12, background: "rgba(34,197,94,0.08)", border: "1px solid rgba(34,197,94,0.25)", borderRadius: 12, padding: "14px 18px", marginBottom: 22 }}>
          <i data-lucide="trophy" style={{ width: 20, height: 20, color: "#22C55E", flexShrink: 0 }}></i>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", textTransform: "uppercase" }}>You won this auction</div>
            <div style={{ fontSize: 12.5, color: "var(--text-2)" }}>Arrange payment within 24 hours to secure your purchase.</div>
          </div>
          {dueAt && <PayClock dueAt={dueAt} />}
        </div>
      )}

      <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 30, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: "0 0 22px" }}>Checkout</h1>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 340px", gap: 22 }} className="eb-form-2">
        {/* Left: payment method */}
        <div>
          {inspectable && (
            <div style={{ ...panelCard, padding: 20, marginBottom: 18 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", textTransform: "uppercase", marginBottom: 14, display: "flex", alignItems: "center", gap: 8 }}><i data-lucide="shield-check" style={{ width: 16, height: 16, color: "#22C55E" }}></i>Protection &amp; warranty</div>
              <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", background: "rgba(34,197,94,0.07)", border: "1px solid rgba(34,197,94,0.2)", borderRadius: 9, marginBottom: 14 }}>
                <i data-lucide="check-circle-2" style={{ width: 17, height: 17, color: "#22C55E", flexShrink: 0 }}></i>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)" }}>90-day guarantee — included</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Engine, hydraulics &amp; drivetrain, from delivery.</div>
                </div>
                <span style={{ fontFamily: "var(--ff-mono)", fontSize: 13, fontWeight: 700, color: "#22C55E" }}>€0</span>
              </div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 9 }}>Extend cover · insurance-backed</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {[
                  { v: "none", t: "No extended cover", s: "Keep the included 90 days", c: 0 },
                  { v: "1y", t: "1-year warranty", s: "Powertrain & hydraulics", c: Math.round(baseAmount * wr.oneYearRate) },
                  { v: "2y", t: "2-year warranty", s: "Best for high-use machines", c: Math.round(baseAmount * wr.twoYearRate) },
                ].map((o) => (
                  <button key={o.v} onClick={() => setWarranty(o.v)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderRadius: 9, cursor: "pointer", textAlign: "left", border: `1px solid ${warranty === o.v ? "#8B5CF6" : "var(--border-s)"}`, background: warranty === o.v ? "rgba(139,92,246,0.08)" : "var(--surface)" }}>
                    <span style={{ width: 18, height: 18, borderRadius: "50%", border: `2px solid ${warranty === o.v ? "#8B5CF6" : "var(--border-s)"}`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{warranty === o.v && <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#8B5CF6" }}></span>}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)" }}>{o.t}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{o.s}</div>
                    </div>
                    <span style={{ fontFamily: "var(--ff-mono)", fontSize: 13, fontWeight: 700, color: "var(--text)" }}>{o.c ? "+" + eur(o.c) : "—"}</span>
                  </button>
                ))}
              </div>
              <button onClick={() => setTransport((t) => !t)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderRadius: 9, cursor: "pointer", textAlign: "left", border: `1px solid ${transport ? "var(--ignite)" : "var(--border-s)"}`, background: transport ? "rgba(249,115,22,0.07)" : "var(--surface)", marginTop: 10 }}>
                <i data-lucide="truck" style={{ width: 18, height: 18, color: transport ? "var(--ignite)" : "var(--text-3)", flexShrink: 0 }}></i>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)" }}>Managed transport <span style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 500 }}>(estimated)</span></div>
                  <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Low-loader, permits &amp; customs to your address.</div>
                </div>
                <span style={{ fontFamily: "var(--ff-mono)", fontSize: 13, fontWeight: 700, color: "var(--text)" }}>+{eur(Math.round(baseAmount * 0.015) + 450)}</span>
              </button>
            </div>
          )}
          {/* method tabs */}
          <div style={{ display: "flex", gap: 10, marginBottom: 18 }}>
            <MethodTab on={method === "card"} onClick={() => setMethod("card")} icon="credit-card" title="Card (Escrow)" sub="Instant · funds held safely" />
            <MethodTab on={method === "wire"} onClick={() => setMethod("wire")} icon="building-2" title="Wire transfer" sub="1–2 business days" />
          </div>

          {method === "card" ? (
            <div style={{ ...panelCard, padding: 22 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", textTransform: "uppercase", marginBottom: 14 }}>Pay into escrow</div>
              {wallet.card ? (
                <div style={{ ...cardRow, justifyContent: "space-between", marginBottom: 14 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <i data-lucide="credit-card" style={{ width: 18, height: 18, color: "var(--text-2)" }}></i>
                    <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text)" }}>{wallet.card.brand} •••• {wallet.card.last4}</span>
                  </span>
                  <button onClick={onAddCard} style={{ fontSize: 12, color: "var(--cobalt)", fontWeight: 700 }}>Change</button>
                </div>
              ) : (
                <button onClick={onAddCard} style={{ ...ghostBtn, width: "100%", justifyContent: "center", marginBottom: 14 }}><i data-lucide="plus" style={{ width: 15, height: 15 }}></i> Add a card</button>
              )}
              <div style={{ display: "flex", gap: 9, fontSize: 12, color: "var(--text-2)", background: "rgba(34,197,94,0.07)", border: "1px solid rgba(34,197,94,0.2)", borderRadius: 8, padding: "11px 13px", marginBottom: 16, lineHeight: 1.5 }}>
                <i data-lucide="shield-check" style={{ width: 16, height: 16, color: "#22C55E", flexShrink: 0 }}></i>
                <span>Your money is held in <strong style={{ color: "var(--text)" }}>escrow</strong> and released to the seller only after the equipment is delivered and inspected.</span>
              </div>
              <button onClick={() => wallet.card ? onPay(item.id, "card", total, mode) : onAddCard()} style={{ ...primaryBtn, width: "100%", justifyContent: "center", padding: "13px", fontSize: 14, background: "#22C55E" }}>
                <i data-lucide="lock" style={{ width: 15, height: 15 }}></i> Pay {eur(total)} into escrow
              </button>
            </div>
          ) : (
            <div style={{ ...panelCard, padding: 22 }}>
              <div style={{ fontSize: 13, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", textTransform: "uppercase", marginBottom: 14 }}>Wire transfer details</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 0, border: "1px solid var(--border)", borderRadius: 10, overflow: "hidden", marginBottom: 14 }}>
                {[
                  ["Beneficiary", "Equipment Balkans Escrow d.o.o."],
                  ["Bank", "Raiffeisen Banka a.d. Beograd"],
                  ["IBAN", "RS35 2600 0560 1001 6113 79"],
                  ["SWIFT / BIC", "RZBSRSBG"],
                  ["Amount", eur(total)],
                  ["Reference", "EB-" + item.id.toUpperCase().slice(0, 8)],
                ].map(([k, v], i) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "11px 14px", background: i % 2 ? "var(--surface)" : "var(--card-bg)", borderBottom: i < 5 ? "1px solid var(--border)" : "none" }}>
                    <span style={{ fontSize: 12, color: "var(--text-3)" }}>{k}</span>
                    <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-mono)", textAlign: "right" }}>{v}</span>
                  </div>
                ))}
              </div>
              <div style={{ display: "flex", gap: 9, fontSize: 12, color: "var(--text-2)", background: "rgba(37,99,235,0.07)", border: "1px solid rgba(37,99,235,0.2)", borderRadius: 8, padding: "11px 13px", marginBottom: 16, lineHeight: 1.5 }}>
                <i data-lucide="info" style={{ width: 16, height: 16, color: "var(--cobalt)", flexShrink: 0 }}></i>
                <span>Use the exact reference so we can match your transfer. Funds land in escrow on receipt.</span>
              </div>
              <button onClick={() => onPay(item.id, "wire", total, mode)} style={{ ...primaryBtn, width: "100%", justifyContent: "center", padding: "13px", fontSize: 14, background: "var(--cobalt)" }}>
                <i data-lucide="check" style={{ width: 15, height: 15 }}></i> I've sent the transfer
              </button>
            </div>
          )}
        </div>

        {/* Right: order summary */}
        <div>
          <div style={{ ...panelCard, padding: 20, position: "sticky", top: "calc(88px + var(--eb-statusbar-h, 0px))" }}>
            <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
              <EquipImage src={item.images[0]} alt="" style={{ width: 72, height: 56, borderRadius: 8, objectFit: "cover", flexShrink: 0 }} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-display)", lineHeight: 1.2 }}>{item.title}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 3 }}>{mode === "buy" ? "Marketplace purchase" : "Auction win"}</div>
              </div>
            </div>
            <Row k={mode === "buy" ? "Item price" : "Hammer price"} v={eur(baseAmount)} />
            <Row k="Buyer's premium (5%)" v={eur(premium)} />
            {warrantyCost > 0 && <Row k={warranty === "1y" ? "1-year warranty" : "2-year warranty"} v={eur(warrantyCost)} />}
            {transportCost > 0 && <Row k="Managed transport (est.)" v={eur(transportCost)} />}
            <div style={{ height: 1, background: "var(--border)", margin: "10px 0" }}></div>
            <Row k="Total" v={eur(total)} big />
            <div style={{ ...lockNote, marginTop: 14 }}><i data-lucide="shield-check" style={{ width: 13, height: 13 }}></i> Buyer protection &amp; escrow included.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PayClock({ dueAt }) {
  const [, f] = usePay(0);
  usePayE(() => { const id = setInterval(() => f((x) => x + 1), 1000); return () => clearInterval(id); }, []);
  const diff = dueAt - Date.now();
  const h = Math.max(0, Math.floor(diff / 3600000));
  const m = Math.max(0, Math.floor((diff % 3600000) / 60000));
  const s = Math.max(0, Math.floor((diff % 60000) / 1000));
  return (
    <div style={{ textAlign: "right" }}>
      <div style={{ fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".08em" }}>Pay within</div>
      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 18, fontWeight: 700, color: diff < 6 * 3600000 ? "var(--ignite)" : "var(--text)", fontVariantNumeric: "tabular-nums" }}>
        {String(h).padStart(2, "0")}:{String(m).padStart(2, "0")}:{String(s).padStart(2, "0")}
      </div>
    </div>
  );
}

// ── Payments tab (inside account) ───────────────────
function PaymentsTab({ wallet, store, onAddCard, onRelease, onReleasePreauth, onNav }) {
  const preauths = Object.entries(wallet.preauths || {});
  const escrow = wallet.escrow || [];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
      {/* Card on file */}
      <div>
        <SectionLabel>Payment method</SectionLabel>
        {wallet.card ? (
          <div style={{ ...panelCard, display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ width: 46, height: 32, borderRadius: 6, background: "linear-gradient(135deg,#1e293b,#334155)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <i data-lucide="credit-card" style={{ width: 18, height: 18, color: "#fff" }}></i>
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>{wallet.card.brand} •••• {wallet.card.last4}</div>
              <div style={{ fontSize: 12, color: "var(--text-3)" }}>Expires {wallet.card.exp} · {wallet.card.name}</div>
            </div>
            <button onClick={onAddCard} style={{ ...ghostBtn, fontSize: 12.5 }}>Replace</button>
          </div>
        ) : (
          <div style={{ ...panelCard, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <span style={{ fontSize: 13, color: "var(--text-3)" }}>No card on file yet.</span>
            <button onClick={onAddCard} style={primaryBtn}><i data-lucide="plus" style={{ width: 15, height: 15 }}></i> Add a card</button>
          </div>
        )}
      </div>

      {/* Pre-auth holds */}
      <div>
        <SectionLabel>Pre-authorization holds</SectionLabel>
        {preauths.length === 0 ? (
          <div style={emptyMini}>No active holds. Holds appear here when you bid on lots over €500.</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {preauths.map(([aid, p]) => {
              const a = store.auctions.find((x) => x.id === aid);
              const released = p.status === "released";
              return (
                <div key={aid} style={{ ...panelCard, display: "flex", alignItems: "center", gap: 13, padding: 14 }}>
                  <i data-lucide={released ? "undo-2" : "shield-check"} style={{ width: 18, height: 18, color: released ? "var(--text-3)" : "var(--cobalt)" }}></i>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a ? a.title : aid}</div>
                    <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{released ? "Released" : "Refundable hold"}</div>
                  </div>
                  <span style={{ fontFamily: "var(--ff-mono)", fontSize: 14, fontWeight: 700, color: released ? "var(--text-3)" : "var(--text)", textDecoration: released ? "line-through" : "none" }}>{eur(p.amount)}</span>
                  {!released && <button onClick={() => onReleasePreauth(aid)} style={{ fontSize: 11.5, color: "var(--cobalt)", fontWeight: 700 }}>Release</button>}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Escrow transactions */}
      <div>
        <SectionLabel>Escrow &amp; purchases</SectionLabel>
        {escrow.length === 0 ? (
          <div style={emptyMini}>No transactions yet. When you win or buy, funds are held safely here until delivery.</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {escrow.map((e) => {
              const a = store.auctions.find((x) => x.id === e.refId);
              return (
                <div key={e.id} style={{ ...panelCard, padding: 16 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 14 }}>
                    {a && <EquipImage src={a.images[0]} alt="" style={{ width: 56, height: 44, borderRadius: 7, objectFit: "cover", flexShrink: 0 }} />}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-display)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a ? a.title : e.title}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{e.method === "wire" ? "Wire transfer" : "Card"} · {new Date(e.createdAt).toLocaleDateString()}</div>
                    </div>
                    <span style={{ fontFamily: "var(--ff-mono)", fontSize: 16, fontWeight: 700, color: "var(--ignite)" }}>{eur(e.amount)}</span>
                  </div>
                  <EscrowTimeline status={e.status} method={e.method} />
                  {e.status !== "released" && (
                    <button onClick={() => onRelease(e.id)} style={{ ...primaryBtn, width: "100%", justifyContent: "center", background: "#22C55E", marginTop: 4 }}>
                      <i data-lucide="check-circle-2" style={{ width: 15, height: 15 }}></i> Confirm delivery &amp; release funds
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Small helpers / styles ──────────────────────────
function PayField({ label, children }) {
  return (<div><label style={fieldLabel}>{label}</label><div style={{ marginTop: 6 }}>{children}</div></div>);
}
function Row({ k, v, big }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "4px 0" }}>
      <span style={{ fontSize: big ? 14 : 12.5, fontWeight: big ? 700 : 500, color: big ? "var(--text)" : "var(--text-3)" }}>{k}</span>
      <span style={{ fontSize: big ? 20 : 13, fontWeight: big ? 800 : 600, color: big ? "var(--ignite)" : "var(--text)", fontFamily: "var(--ff-mono)" }}>{v}</span>
    </div>
  );
}
function MethodTab({ on, onClick, icon, title, sub }) {
  return (
    <button onClick={onClick} style={{ flex: 1, textAlign: "left", padding: "13px 15px", borderRadius: 10, cursor: "pointer", border: `1px solid ${on ? "var(--ignite)" : "var(--border-s)"}`, background: on ? "rgba(249,115,22,0.07)" : "var(--surface)" }}>
      <i data-lucide={icon} style={{ width: 18, height: 18, color: on ? "var(--ignite)" : "var(--text-3)" }}></i>
      <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)", marginTop: 7 }}>{title}</div>
      <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 1 }}>{sub}</div>
    </button>
  );
}
function SectionLabel({ children }) {
  return <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 12 }}>{children}</div>;
}
const payErr = { display: "flex", alignItems: "center", gap: 8, background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.25)", borderRadius: 6, padding: "9px 12px", fontSize: 12.5, color: "#F87171" };
const lockNote = { display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--text-3)" };
const cardRow = { display: "flex", alignItems: "center", gap: 9, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 8, padding: "10px 12px" };
const backLink = { display: "inline-flex", alignItems: "center", gap: 6, color: "var(--text-2)", fontSize: 12.5, fontWeight: 600, marginBottom: 18 };
const gateIcon = (c) => ({ width: 44, height: 44, borderRadius: 10, background: c === "var(--cobalt)" ? "rgba(37,99,235,0.12)" : "rgba(249,115,22,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 });
const gateTitle = { fontSize: 15.5, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", marginBottom: 5 };
const gateSub = { fontSize: 12.5, color: "var(--text-3)", marginBottom: 14, lineHeight: 1.5 };
const emptyMini = { fontSize: 13, color: "var(--text-3)", background: "var(--surface)", border: "1px dashed var(--border-s)", borderRadius: 10, padding: "18px 16px", textAlign: "center" };

Object.assign(window, { AddCardModal, PreauthModal, BidGate, CheckoutScreen, PaymentsTab, EscrowTimeline, preauthFor, HIGH_VALUE_THRESHOLD });
