// cart.jsx — Cart, Checkout, Confirmation. Multi-product-ready.
// Loaded after sections-*.jsx, before main.jsx. Exposes CartProvider, useCart, CartButton,
// CartDrawer, CheckoutOverlay, OrderConfirmation, PRODUCTS, PICKUP_SLOTS, PAYMENT_METHODS.

const { createContext: rdbCreateContext, useContext: rdbUseContext } = React;

// ─── CONFIG — edit here to add products, slots, payment methods ──────────────
// To add a new product later, append an entry. tiers[] is the size/price ladder
// for that product. The cart understands any tier from any product.
const PRODUCTS = {
  'real-date-bar': {
    id: 'real-date-bar',
    name: 'Real Date Bar',
    blurb: 'Organic dates + organic cashews. Two ingredients.',
    image: 'uploads/DSC02390.jpeg',
    tiers: [
      { id: 'single', label: 'Single bar', qty: 1,  price: 5  },
      { id: 'five',   label: '5-pack',     qty: 5,  price: 22, featured: true },
      { id: 'ten',    label: '10-pack',    qty: 10, price: 40 },
    ],
  },
  // FUTURE PRODUCT example — uncomment & rename to add a 2nd bar:
  // 'chocolate-date-bar': {
  //   id: 'chocolate-date-bar', name: 'Chocolate Date Bar',
  //   blurb: 'Dates + cashews dipped in dark chocolate.',
  //   image: 'uploads/chocolate.jpeg',
  //   tiers: [
  //     { id: 'single', label: 'Single bar', qty: 1, price: 6 },
  //     { id: 'five',   label: '5-pack',     qty: 5, price: 26, featured: true },
  //   ],
  // },
};

// Weekly recurring pickup windows. Ela picks the actual date with each customer.
// To add/remove slots, edit this list and re-upload cart.jsx.
const PICKUP_SLOTS = [
  { id: 'sat-am',   label: 'Saturday morning · 9–11 AM' },
  { id: 'sat-pm',   label: 'Saturday afternoon · 1–3 PM' },
  { id: 'sat-eve',  label: 'Saturday evening · 4–6 PM' },
  { id: 'sun-am',   label: 'Sunday morning · 10 AM–12 PM' },
  { id: 'sun-pm',   label: 'Sunday afternoon · 2–4 PM' },
  { id: 'flexible', label: "I'll work out a time with Ela" },
];

const PAYMENT_METHODS = ['Venmo', 'Zelle', 'Apple Pay', 'PayPal', 'Cash'];

// ─── Order number generator ──────────────────────────────────────────────────
// RDB-YYYYMMDD-XXXX where XXXX is 4 unambiguous uppercase chars (no 0/O/1/I).
function makeOrderNumber() {
  const d = new Date();
  const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  let suffix = '';
  for (let i = 0; i < 4; i++) suffix += chars[Math.floor(Math.random() * chars.length)];
  return `RDB-${ymd}-${suffix}`;
}

// ─── Cart context ────────────────────────────────────────────────────────────
const CART_KEY = 'rdb_cart_v1';
const CartContext = rdbCreateContext(null);

function CartProvider({ children }) {
  const [items, setItems] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(CART_KEY) || '[]') || []; }
    catch { return []; }
  });
  const [drawerOpen, setDrawerOpen]   = React.useState(false);
  const [checkoutOpen, setCheckoutOpen] = React.useState(false);
  const [confirmation, setConfirmation] = React.useState(null);

  React.useEffect(() => {
    try { localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch {}
  }, [items]);

  // Sanitize: drop any line that no longer matches a known product/tier
  React.useEffect(() => {
    const filtered = items.filter(it => {
      const p = PRODUCTS[it.productId];
      return !!(p && p.tiers.some(t => t.id === it.tierId));
    });
    if (filtered.length !== items.length) setItems(filtered);
  }, []); // run once on mount

  const addItem = (productId, tierId, qty = 1) => {
    setItems(prev => {
      const idx = prev.findIndex(it => it.productId === productId && it.tierId === tierId);
      if (idx >= 0) {
        const next = [...prev];
        next[idx] = { ...next[idx], qty: next[idx].qty + qty };
        return next;
      }
      return [...prev, { productId, tierId, qty }];
    });
    setDrawerOpen(true);
  };

  const setItemQty = (productId, tierId, qty) => {
    setItems(prev => {
      if (qty <= 0) return prev.filter(it => !(it.productId === productId && it.tierId === tierId));
      return prev.map(it =>
        (it.productId === productId && it.tierId === tierId) ? { ...it, qty } : it
      );
    });
  };

  const removeItem = (productId, tierId) => setItemQty(productId, tierId, 0);
  const clearCart  = () => setItems([]);

  // Hydrate with product/tier details
  const lines = items.map(it => {
    const product = PRODUCTS[it.productId];
    const tier    = product && product.tiers.find(t => t.id === it.tierId);
    if (!product || !tier) return null;
    return {
      productId: it.productId, tierId: it.tierId, qty: it.qty,
      productName: product.name,
      tierLabel:   tier.label,
      unitPrice:   tier.price,
      barsPerUnit: tier.qty,
      lineTotal:   tier.price * it.qty,
      lineBars:    tier.qty   * it.qty,
    };
  }).filter(Boolean);

  const itemCount = lines.reduce((s, l) => s + l.qty, 0);
  const totalBars = lines.reduce((s, l) => s + l.lineBars, 0);
  const subtotal  = lines.reduce((s, l) => s + l.lineTotal, 0);

  return (
    <CartContext.Provider value={{
      items, lines, itemCount, totalBars, subtotal,
      addItem, setItemQty, removeItem, clearCart,
      drawerOpen, setDrawerOpen,
      checkoutOpen, setCheckoutOpen,
      confirmation, setConfirmation,
    }}>
      {children}
    </CartContext.Provider>
  );
}

const useCart = () => rdbUseContext(CartContext);

// ─── Cart icon button (for Nav) ──────────────────────────────────────────────
function CartButton() {
  const cart = useCart();
  if (!cart) return null;
  const { itemCount, setDrawerOpen } = cart;
  return (
    <button
      type="button"
      className="cart-btn"
      aria-label={`Cart (${itemCount} item${itemCount === 1 ? '' : 's'})`}
      onClick={() => setDrawerOpen(true)}
      style={{
        background: 'transparent', border: '1px solid var(--line-strong)',
        width: 42, height: 42, borderRadius: 999, padding: 0,
        color: 'var(--ink)', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative',
      }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
        strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M3 7h18l-2 12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L3 7Z"/>
        <path d="M8 7l2-4h4l2 4"/>
      </svg>
      {itemCount > 0 && (
        <span style={{
          position: 'absolute', top: -4, right: -4,
          minWidth: 18, height: 18, padding: '0 5px',
          borderRadius: 999, background: 'var(--accent)', color: 'var(--paper)',
          fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700,
          letterSpacing: '.02em',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          border: '2px solid var(--bg)',
        }}>{itemCount}</span>
      )}
    </button>
  );
}

// ─── Cart drawer ─────────────────────────────────────────────────────────────
const qtyBtnStyle = {
  width: 34, height: 34, padding: 0, border: 0,
  background: 'transparent', color: 'var(--ink)',
  fontFamily: 'var(--display)', fontSize: 18, cursor: 'pointer',
};

function CartDrawer() {
  const cart = useCart();
  if (!cart) return null;
  const { drawerOpen, setDrawerOpen, lines, subtotal, totalBars, setItemQty, removeItem, setCheckoutOpen } = cart;

  React.useEffect(() => {
    if (!drawerOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [drawerOpen]);

  React.useEffect(() => {
    if (!drawerOpen) return;
    const on = (e) => { if (e.key === 'Escape') setDrawerOpen(false); };
    window.addEventListener('keydown', on);
    return () => window.removeEventListener('keydown', on);
  }, [drawerOpen, setDrawerOpen]);

  if (!drawerOpen) return null;

  const goToCheckout = () => {
    setDrawerOpen(false);
    setCheckoutOpen(true);
    if (window.location.hash !== '#checkout') {
      history.pushState({ checkout: true }, '', '#checkout');
    }
  };

  return (
    <div onClick={() => setDrawerOpen(false)} style={{
      position: 'fixed', inset: 0, zIndex: 90,
      background: 'rgba(20, 12, 4, 0.42)',
      backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
      animation: 'rdbFadeIn .18s ease',
    }}>
      <aside onClick={e => e.stopPropagation()} role="dialog" aria-label="Cart"
        style={{
          position: 'absolute', right: 0, top: 0, bottom: 0,
          width: 'min(420px, 100%)',
          background: 'var(--bg)', borderLeft: '1px solid var(--line-strong)',
          display: 'flex', flexDirection: 'column',
          animation: 'rdbSlideInRight .25s cubic-bezier(.2,.8,.2,1)',
        }}>
        <div style={{
          padding: '20px 24px', borderBottom: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16,
        }}>
          <div>
            <span className="eyebrow">Your cart</span>
            <h3 style={{ marginTop: 8, fontSize: 26 }}>
              {lines.length === 0 ? 'Still empty' : `${totalBars} bar${totalBars === 1 ? '' : 's'}`}
            </h3>
          </div>
          <button type="button" aria-label="Close cart" onClick={() => setDrawerOpen(false)}
            style={{
              background: 'transparent', border: '1px solid var(--line-strong)',
              width: 38, height: 38, borderRadius: 999, padding: 0,
              fontSize: 20, color: 'var(--ink)', cursor: 'pointer', lineHeight: 1, flexShrink: 0,
            }}>×</button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 24px' }}>
          {lines.length === 0 ? (
            <div style={{ padding: '32px 0', textAlign: 'center', color: 'var(--ink-soft)' }}>
              <p style={{ fontFamily: 'var(--display)', fontSize: 22 }}>Your cart is waiting.</p>
              <p style={{ marginTop: 12, fontSize: 14 }}>
                Pick a pack from the pricing section to get started.
              </p>
              <button type="button" className="btn ghost"
                onClick={() => {
                  setDrawerOpen(false);
                  setTimeout(() => document.querySelector('#pricing')?.scrollIntoView({ behavior: 'smooth' }), 80);
                }}
                style={{ marginTop: 24 }}>
                See packs <span className="arr">→</span>
              </button>
            </div>
          ) : (
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
              {lines.map(l => (
                <li key={`${l.productId}-${l.tierId}`} style={{
                  padding: 16, border: '1px solid var(--line)', borderRadius: 'var(--radius)',
                  background: 'var(--paper)', display: 'flex', flexDirection: 'column', gap: 12,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                    <div>
                      <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>{l.productName}</div>
                      <div style={{ fontFamily: 'var(--display)', fontSize: 22, marginTop: 4 }}>{l.tierLabel}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontFamily: 'var(--display)', fontSize: 22 }}>${l.lineTotal}</div>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>${l.unitPrice} ea</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--line-strong)', borderRadius: 999, overflow: 'hidden' }}>
                      <button type="button" aria-label="decrease"
                        onClick={() => setItemQty(l.productId, l.tierId, l.qty - 1)}
                        style={qtyBtnStyle}>−</button>
                      <span style={{ minWidth: 28, textAlign: 'center', fontFamily: 'var(--display)', fontSize: 18 }}>{l.qty}</span>
                      <button type="button" aria-label="increase"
                        onClick={() => setItemQty(l.productId, l.tierId, l.qty + 1)}
                        style={qtyBtnStyle}>+</button>
                    </div>
                    <button type="button" onClick={() => removeItem(l.productId, l.tierId)}
                      style={{ background: 'transparent', border: 0, color: 'var(--ink-mute)',
                        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em',
                        textTransform: 'uppercase', cursor: 'pointer' }}>
                      Remove
                    </button>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        {lines.length > 0 && (
          <div style={{
            padding: 24, borderTop: '1px solid var(--line-strong)',
            background: 'var(--bg-soft)',
            display: 'flex', flexDirection: 'column', gap: 16,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Subtotal</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', marginTop: 4 }}>
                  Pickup only · Frisco, TX
                </div>
              </div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 36, lineHeight: 1 }}>${subtotal}</div>
            </div>
            <button type="button" className="btn" onClick={goToCheckout}
              style={{ width: '100%', justifyContent: 'center', padding: '16px 20px' }}>
              Checkout <span className="arr">→</span>
            </button>
          </div>
        )}
      </aside>
    </div>
  );
}

// ─── Checkout overlay ────────────────────────────────────────────────────────
function CheckoutOverlay() {
  const cart = useCart();
  if (!cart) return null;
  const { checkoutOpen, setCheckoutOpen, lines, subtotal, totalBars, clearCart,
          confirmation, setConfirmation } = cart;

  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [slot, setSlot] = React.useState('');
  const [pay, setPay] = React.useState('Venmo');
  const [notes, setNotes] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState('');

  const closeCheckout = React.useCallback(() => {
    setCheckoutOpen(false);
    setConfirmation(null);
    setErr('');
    if (window.location.hash === '#checkout') {
      history.replaceState(null, '', window.location.pathname + window.location.search);
    }
  }, [setCheckoutOpen, setConfirmation]);

  // Esc closes
  React.useEffect(() => {
    if (!checkoutOpen) return;
    const on = (e) => { if (e.key === 'Escape' && !submitting) closeCheckout(); };
    window.addEventListener('keydown', on);
    return () => window.removeEventListener('keydown', on);
  }, [checkoutOpen, submitting, closeCheckout]);

  // Lock body scroll
  React.useEffect(() => {
    if (!checkoutOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [checkoutOpen]);

  // Back button exits checkout but preserves cart
  React.useEffect(() => {
    if (!checkoutOpen) return;
    const on = () => closeCheckout();
    window.addEventListener('popstate', on);
    return () => window.removeEventListener('popstate', on);
  }, [checkoutOpen, closeCheckout]);

  if (!checkoutOpen) return null;

  // If we have a confirmation, render that instead of the form.
  if (confirmation) {
    return <OrderConfirmation onClose={closeCheckout} {...confirmation} />;
  }

  // No items? Bail back to homepage.
  if (lines.length === 0) {
    return (
      <div style={overlayStyle}>
        <div style={{ ...checkoutCardStyle, maxWidth: 480, textAlign: 'center', padding: 'clamp(28px, 5vw, 48px)' }}>
          <span className="eyebrow">Checkout</span>
          <h2 style={{ marginTop: 12 }}>Your cart is empty.</h2>
          <p style={{ marginTop: 16, color: 'var(--ink-soft)' }}>Add a pack first, then come back.</p>
          <button type="button" className="btn" onClick={closeCheckout} style={{ marginTop: 24 }}>
            Back to the bar <span className="arr">→</span>
          </button>
        </div>
      </div>
    );
  }

  const submit = (e) => {
    e.preventDefault();
    if (!slot) { setErr('Please pick a pickup window.'); return; }
    setSubmitting(true); setErr('');

    const orderNumber = makeOrderNumber();
    const slotLabel = (PICKUP_SLOTS.find(s => s.id === slot) || {}).label || slot;
    const packLine  = lines.map(l => `${l.qty}× ${l.tierLabel}`).join(' + ');

    const payload = {
      orderNumber,
      // legacy fields preserved for back-compat with old order.php
      name, contact: email, carrier: '',
      pack: packLine,
      price: String(subtotal),
      payment: pay,
      pickup: slotLabel,
      notes: notes || '—',
      // new structured fields
      items: lines.map(l => ({
        productId: l.productId, productName: l.productName,
        tierId: l.tierId, tierLabel: l.tierLabel,
        qty: l.qty, unitPrice: l.unitPrice, lineTotal: l.lineTotal, bars: l.lineBars,
      })),
      subtotal, totalBars,
      pickupSlot: { id: slot, label: slotLabel },
    };

    fetch('/order.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })
      .then(r => r.json())
      .then(d => {
        if (d.success) {
          setConfirmation({
            orderNumber, lines: [...lines], subtotal, totalBars,
            slotLabel, payment: pay, name, email,
          });
          clearCart();
          setSubmitting(false);
        } else {
          setErr('Something went wrong. Please email ela@realdatebar.com directly.');
          setSubmitting(false);
        }
      })
      .catch(() => {
        setErr('Network error. Please email ela@realdatebar.com directly.');
        setSubmitting(false);
      });
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px', borderRadius: 10,
    border: '1px solid var(--line-strong)', background: 'var(--paper)',
    fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)', outline: 'none',
  };
  const labelStyle = {
    fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em',
    textTransform: 'uppercase', color: 'var(--ink-mute)',
    display: 'block', marginBottom: 8,
  };

  return (
    <div style={overlayStyle}>
      <div className="checkout-card" style={checkoutCardStyle}>
        <header style={{
          padding: '18px 24px', borderBottom: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
          background: 'var(--bg)',
          position: 'sticky', top: 0, zIndex: 2,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontFamily: 'var(--display)', fontSize: 22 }}>
              Real <span style={{ fontStyle: 'italic' }}>Date Bar</span>
            </span>
            <span className="mono uppercase" style={{ color: 'var(--ink-mute)' }}>· Checkout</span>
          </div>
          <button type="button" aria-label="Close checkout" onClick={closeCheckout}
            disabled={submitting}
            style={{
              background: 'transparent', border: '1px solid var(--line-strong)',
              width: 38, height: 38, borderRadius: 999, padding: 0,
              fontSize: 20, color: 'var(--ink)', cursor: submitting ? 'wait' : 'pointer', lineHeight: 1,
            }}>×</button>
        </header>

        <div className="checkout-grid" style={{
          display: 'grid', gridTemplateColumns: '1fr 1.1fr',
          flex: 1, minHeight: 0,
        }}>
          {/* Order summary */}
          <section className="checkout-summary" style={{
            background: 'var(--bg-soft)', borderRight: '1px solid var(--line)',
            padding: 'clamp(24px, 3vw, 40px)', overflowY: 'auto',
            display: 'flex', flexDirection: 'column', gap: 20,
          }}>
            <div>
              <span className="eyebrow">Order summary</span>
              <h3 style={{ marginTop: 8, fontSize: 24 }}>
                {totalBars} bar{totalBars === 1 ? '' : 's'} · ${subtotal}
              </h3>
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
              {lines.map(l => (
                <li key={`${l.productId}-${l.tierId}`} style={{
                  padding: 14, background: 'var(--paper)',
                  border: '1px solid var(--line)', borderRadius: 'var(--radius)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
                }}>
                  <div>
                    <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>{l.productName}</div>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 18, marginTop: 2 }}>{l.qty}× {l.tierLabel}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 20 }}>${l.lineTotal}</div>
                  </div>
                </li>
              ))}
            </ul>
            <div style={{ borderTop: '1px solid var(--line-strong)', paddingTop: 16, marginTop: 'auto', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Subtotal</div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 32 }}>${subtotal}</div>
            </div>
            <p className="mono" style={{ fontSize: 11, letterSpacing: '.08em', color: 'var(--ink-mute)' }}>
              Pickup only · 13030 Dolomite Drive, Frisco TX · Pay on pickup
            </p>
          </section>

          {/* Form */}
          <form onSubmit={submit} style={{
            padding: 'clamp(24px, 3vw, 40px)', overflowY: 'auto',
            display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <div>
              <span className="eyebrow">Your details</span>
              <h3 style={{ marginTop: 8, fontSize: 24 }}>Tell Ela where to find you.</h3>
            </div>

            <div>
              <label style={labelStyle}>Your name</label>
              <input style={inputStyle} value={name} onChange={e => setName(e.target.value)}
                required placeholder="Jordan Reeves" autoComplete="name" />
            </div>

            <div>
              <label style={labelStyle}>Email</label>
              <input type="email" style={inputStyle} value={email} onChange={e => setEmail(e.target.value)}
                required placeholder="you@example.com" autoComplete="email" />
              <p style={{ margin: '8px 0 0', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '.06em' }}>
                We'll send your order receipt here.
              </p>
            </div>

            <div>
              <label style={labelStyle}>Pickup window</label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {PICKUP_SLOTS.map(s => (
                  <button key={s.id} type="button" onClick={() => setSlot(s.id)}
                    style={{
                      padding: '14px 12px', borderRadius: 10, textAlign: 'left',
                      border: '1px solid ' + (slot === s.id ? 'var(--ink)' : 'var(--line-strong)'),
                      background: slot === s.id ? 'var(--ink)' : 'transparent',
                      color: slot === s.id ? 'var(--bg)' : 'var(--ink)',
                      fontFamily: 'var(--sans)', fontSize: 13, lineHeight: 1.3,
                      cursor: 'pointer', transition: 'all .15s ease',
                    }}>
                    {s.label}
                  </button>
                ))}
              </div>
              <p style={{ margin: '8px 0 0', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '.06em' }}>
                Ela will confirm the exact date by email.
              </p>
            </div>

            <div>
              <label style={labelStyle}>Payment method</label>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {PAYMENT_METHODS.map(p => (
                  <button type="button" key={p} onClick={() => setPay(p)}
                    style={{
                      padding: '10px 14px', borderRadius: 999,
                      border: '1px solid ' + (pay === p ? 'var(--ink)' : 'var(--line-strong)'),
                      background: pay === p ? 'var(--ink)' : 'transparent',
                      color: pay === p ? 'var(--bg)' : 'var(--ink)',
                      fontSize: 13, transition: 'all .15s', cursor: 'pointer',
                    }}>{p}</button>
                ))}
              </div>
              <p style={{ margin: '8px 0 0', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '.06em' }}>
                You'll pay Ela on pickup — or send in advance, your choice.
              </p>
            </div>

            <div>
              <label style={labelStyle}>Notes (optional)</label>
              <textarea style={{ ...inputStyle, minHeight: 72, fontFamily: 'var(--sans)' }}
                value={notes} onChange={e => setNotes(e.target.value)}
                placeholder="Team order, allergies to flag, etc." />
            </div>

            {err && (
              <p style={{
                color: '#c0392b', fontFamily: 'var(--mono)', fontSize: 12,
                padding: '12px 14px', borderRadius: 8,
                background: 'rgba(192, 57, 43, 0.08)', border: '1px solid rgba(192, 57, 43, 0.25)',
              }}>{err}</p>
            )}

            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Total</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 32, lineHeight: 1 }}>${subtotal}</div>
              </div>
              <button type="submit" className="btn" disabled={submitting}
                style={{ padding: '16px 28px', minWidth: 180, justifyContent: 'center' }}>
                {submitting ? 'Placing order…' : 'Place order'}
                {!submitting && <span className="arr">→</span>}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

const overlayStyle = {
  position: 'fixed', inset: 0, zIndex: 95,
  background: 'rgba(20, 12, 4, 0.6)',
  backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
  display: 'flex', alignItems: 'stretch', justifyContent: 'center',
  padding: 'clamp(0px, 2vw, 24px)',
  animation: 'rdbFadeIn .2s ease',
};
const checkoutCardStyle = {
  background: 'var(--bg)', width: '100%', maxWidth: 1100,
  borderRadius: 'var(--radius-lg)', overflow: 'hidden',
  border: '1px solid var(--line-strong)',
  display: 'flex', flexDirection: 'column',
  maxHeight: '100%',
  boxShadow: '0 40px 80px rgba(20, 12, 4, 0.35)',
  animation: 'rdbScaleIn .25s cubic-bezier(.2,.8,.2,1)',
};

// ─── Order confirmation ──────────────────────────────────────────────────────
function OrderConfirmation({ orderNumber, lines, subtotal, totalBars, slotLabel, payment, name, email, onClose }) {
  return (
    <div style={overlayStyle}>
      <div className="checkout-card" style={checkoutCardStyle}>
        <header style={{
          padding: '18px 24px', borderBottom: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
          background: 'var(--bg)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontFamily: 'var(--display)', fontSize: 22 }}>
              Real <span style={{ fontStyle: 'italic' }}>Date Bar</span>
            </span>
            <span className="mono uppercase" style={{ color: 'var(--ink-mute)' }}>· Order confirmed</span>
          </div>
          <button type="button" aria-label="Close" onClick={onClose}
            style={{
              background: 'transparent', border: '1px solid var(--line-strong)',
              width: 38, height: 38, borderRadius: 999, padding: 0,
              fontSize: 20, color: 'var(--ink)', cursor: 'pointer', lineHeight: 1,
            }}>×</button>
        </header>

        <div style={{ padding: 'clamp(24px, 4vw, 56px)', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 32, maxWidth: 720, margin: '0 auto', width: '100%' }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{
              width: 64, height: 64, borderRadius: 999, margin: '0 auto 16px',
              background: 'var(--accent)', color: 'var(--paper)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--display)', fontSize: 32, lineHeight: 1,
            }}>✓</div>
            <span className="eyebrow diamond">Order confirmed</span>
            <h2 style={{ marginTop: 12 }}>
              Thanks, <em>{name.split(' ')[0] || 'friend'}</em>.
            </h2>
            <p style={{ marginTop: 16, color: 'var(--ink-soft)', maxWidth: 480, margin: '16px auto 0', fontSize: 17 }}>
              We sent a receipt to <strong>{email}</strong>. Ela will reply within a few hours with your exact pickup time.
            </p>
          </div>

          <div style={{
            background: 'var(--paper)', border: '1px solid var(--line)',
            borderRadius: 'var(--radius-lg)', padding: 'clamp(20px, 3vw, 32px)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap', gap: 12, borderBottom: '1px solid var(--line)', paddingBottom: 16, marginBottom: 16 }}>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Order number</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 18, marginTop: 6, letterSpacing: '.04em' }}>{orderNumber}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Total</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 28, marginTop: 4 }}>${subtotal}</div>
              </div>
            </div>

            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {lines.map(l => (
                <li key={`${l.productId}-${l.tierId}`} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                  <div>
                    <span style={{ fontFamily: 'var(--display)', fontSize: 18 }}>{l.qty}× {l.tierLabel}</span>
                    <span className="mono" style={{ marginLeft: 8, fontSize: 11, color: 'var(--ink-mute)' }}>· {l.productName}</span>
                  </div>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--ink-soft)' }}>${l.lineTotal}</span>
                </li>
              ))}
            </ul>

            <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, borderTop: '1px solid var(--line)', paddingTop: 16 }}>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Pickup window</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 18, marginTop: 4 }}>{slotLabel}</div>
              </div>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Payment</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 18, marginTop: 4 }}>{payment}</div>
              </div>
            </div>

            <div style={{ marginTop: 24, padding: 16, background: 'var(--bg-soft)', borderRadius: 'var(--radius)', border: '1px solid var(--line)' }}>
              <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Pickup address</div>
              <div style={{ fontFamily: 'var(--display)', fontSize: 18, marginTop: 6, lineHeight: 1.3 }}>
                13030 Dolomite Drive<br/>Frisco, TX 75035
              </div>
              <a href={`https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent('13030 Dolomite Drive, Frisco, TX 75035')}`}
                target="_blank" rel="noreferrer"
                style={{
                  display: 'inline-block', marginTop: 12,
                  fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em',
                  textTransform: 'uppercase', color: 'var(--accent)',
                  borderBottom: '1px solid var(--accent)',
                }}>
                Get directions →
              </a>
            </div>
          </div>

          <div style={{ textAlign: 'center' }}>
            <button type="button" className="btn ghost" onClick={onClose}>
              Back to the homepage
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Expose ──────────────────────────────────────────────────────────────────
Object.assign(window, {
  PRODUCTS, PICKUP_SLOTS, PAYMENT_METHODS,
  CartProvider, useCart, CartButton, CartDrawer, CheckoutOverlay, OrderConfirmation,
  makeOrderNumber,
});
