// GiftShop.jsx — merged same-day + founder delivery with cart & wishlist

// ── shared pincode logic (used by CartDrawer too) ───────────────────────────
const GS_SAME_DAY_PINS = {
  '400':'Mumbai','401':'Mumbai','410':'Navi Mumbai',
  '110':'Delhi NCR','201':'Noida / Gzb','122':'Gurugram',
  '560':'Bengaluru','500':'Hyderabad','411':'Pune',
  '600':'Chennai','700':'Kolkata','380':'Ahmedabad','302':'Jaipur'
};
const GS_NO_SERVICE = ['190','191','192','193','194','737','738','744','796','797','798','799'];
function gsCheckPin(pin) {
  if (!/^\d{6}$/.test(pin)) return { status: 'invalid' };
  const p3 = pin.slice(0, 3);
  if (GS_NO_SERVICE.includes(p3)) return { status: 'none' };
  if (GS_SAME_DAY_PINS[p3]) return { status: 'same-day', city: GS_SAME_DAY_PINS[p3] };
  return { status: 'next-day' };
}
window.gsCheckPin = gsCheckPin;

// ── product data ─────────────────────────────────────────────────────────────
const GS_BOXES = [
  { id: 'petite', name: 'Petite Bliss Box',  count: '6 hand-rolled bites',       price: 599,  img: 'assets/truffles-board.jpg', tag: 'BESTSELLER' },
  { id: 'queen',  name: 'The Queen Box',     count: '12 assorted · velvet', price: 1199, img: 'assets/box-assorted.jpg',   tag: 'CLASSIC' },
  { id: 'royal',  name: 'Royal Almond Tray', count: '24 pieces · gold seal',price: 1899, img: 'assets/duet-split.jpg',     tag: 'PREMIUM' },
  { id: 'duet',   name: 'Cocoa Duet Bars',   count: '3 loaded bars',             price: 899,  img: 'assets/bars-duo.jpg',       tag: 'BARS' }
];
const GS_ADDONS = [
  { id: 'wrap',     name: 'Velvet gift wrap',       price: 99,  desc: 'Burgundy silk, gold seal.' },
  { id: 'monogram', name: 'Monogram on the lid',    price: 199, desc: 'Foil-pressed initials.' },
  { id: 'rose',     name: 'Single rose, hand-tied', price: 149, desc: 'A real stem, in the box.' },
  { id: 'card',     name: 'Premium cotton card',    price: 79,  desc: 'Letter-pressed, deckle edge.' }
];
const GS_DELIVERY_SLOTS = [
  { id: 'today-eve', when: 'Today',    range: '5 PM – 9 PM',  fee: 0,   tag: 'STANDARD',  cutoffH: 16 },
  { id: 'today-exp', when: 'Today',    range: 'Within 3 hours',    fee: 199, tag: 'EXPRESS',   cutoffH: 18 },
  { id: 'today-mid', when: 'Today',    range: 'Midnight surprise',  fee: 249, tag: 'MIDNIGHT',  cutoffH: 22 },
  { id: 'tom-am',    when: 'Tomorrow', range: '8 AM – 12 PM', fee: 0,   tag: 'MORNING',   cutoffH: 99 },
  { id: 'tom-pm',    when: 'Tomorrow', range: '4 PM – 8 PM',  fee: 0,   tag: 'EVENING',   cutoffH: 99 }
];
const GS_FD_CITIES = ['Mumbai', 'Delhi NCR', 'Bengaluru'];
const GS_FD_SLOTS  = [
  { id: 'morning',   label: 'Morning',   range: '9 AM – 12 PM' },
  { id: 'afternoon', label: 'Afternoon', range: '1 PM – 4 PM'  },
  { id: 'evening',   label: 'Evening',   range: '5 PM – 8 PM'  },
];
window.GS_ADDONS          = GS_ADDONS;
window.GS_DELIVERY_SLOTS  = GS_DELIVERY_SLOTS;

// ── sub-components ───────────────────────────────────────────────────────────
function GS_HeartBtn({ id, name }) {
  const [wished, setWished] = React.useState(window.BB_STORE.inWishlist(id));
  React.useEffect(() => {
    const upd = () => setWished(window.BB_STORE.inWishlist(id));
    window.addEventListener('bb-wishlist-update', upd);
    return () => window.removeEventListener('bb-wishlist-update', upd);
  }, [id]);
  return (
    <button
      title={wished ? 'Remove from wishlist' : 'Save to wishlist'}
      onClick={(e) => { e.stopPropagation(); window.BB_STORE.toggleWishlist(id, name); }}
      style={{
        position: 'absolute', top: 12, right: 12, width: 34, height: 34, borderRadius: '50%',
        background: wished ? 'var(--bb-burgundy)' : 'rgba(250,246,236,0.85)',
        border: wished ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', transition: 'all 220ms', backdropFilter: 'blur(4px)',
        boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
      }}>
      <svg width="16" height="16" viewBox="0 0 24 24"
        fill={wished ? 'var(--bb-gold-light)' : 'none'}
        stroke={wished ? 'var(--bb-gold)' : 'var(--bb-burgundy)'}
        strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
      </svg>
    </button>
  );
}

function GS_ProductCard({ box }) {
  const [hover, setHover] = React.useState(false);
  const [added, setAdded] = React.useState(false);

  const handleAdd = () => {
    window.BB_STORE.addToCart({ id: box.id, name: box.name, price: box.price, img: box.img, tag: box.tag, count: box.count });
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };

  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        background: 'var(--bb-pearl)', borderRadius: 18, overflow: 'hidden',
        border: hover ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)',
        boxShadow: hover ? 'var(--shadow-2)' : 'var(--shadow-1)',
        transform: hover ? 'translateY(-3px)' : 'none',
        transition: 'all 260ms cubic-bezier(0.22,0.61,0.36,1)',
        display: 'flex', flexDirection: 'column', position: 'relative'
      }}>
      {/* Tag badge */}
      <div style={{ position: 'absolute', top: 12, left: 12, zIndex: 2, background: 'var(--bb-burgundy)', color: 'var(--bb-gold-light)', fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.22em', padding: '4px 10px', borderRadius: 999 }}>{box.tag}</div>
      {/* Wishlist button */}
      <GS_HeartBtn id={box.id} name={box.name} />
      {/* Image */}
      <div style={{ aspectRatio: '4/3', overflow: 'hidden', background: 'var(--bb-cocoa)' }}>
        <img src={box.img} alt={box.name} style={{ width: '100%', height: '100%', objectFit: 'cover', transform: hover ? 'scale(1.05)' : 'none', transition: 'transform 800ms cubic-bezier(0.22,0.61,0.36,1)' }} />
      </div>
      {/* Info */}
      <div style={{ padding: '18px 20px 20px', flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 20, color: 'var(--bb-burgundy-deep)', fontWeight: 500, lineHeight: 1.15 }}>{box.name}</div>
        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 13, color: 'var(--fg-3)', fontStyle: 'italic' }}>{box.count}</div>
        <div style={{ marginTop: 'auto', paddingTop: 14, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <span style={{ fontFamily: 'var(--font-serif)', fontSize: 24, color: 'var(--bb-burgundy-deep)', fontWeight: 600 }}>&#8377;{box.price.toLocaleString('en-IN')}</span>
          <button
            onClick={handleAdd}
            style={{
              fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.18em', padding: '10px 18px',
              borderRadius: 999, cursor: 'pointer', border: 'none', transition: 'all 220ms',
              background: added ? 'var(--success)' : 'var(--bb-burgundy)',
              color: added ? '#fff' : 'var(--bb-gold-light)',
              boxShadow: added ? '0 2px 10px rgba(63,122,77,0.35)' : '0 2px 10px rgba(91,31,46,0.3)'
            }}>
            {added ? '✓ ADDED' : '+ ADD TO CART'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── pin banner used by CartDrawer too ────────────────────────────────────────
function GS_PinBanner({ r }) {
  const MAP = {
    'same-day': { bg: 'rgba(79,107,58,0.10)', bd: 'rgba(79,107,58,0.40)', fg: '#3F5A2A', title: 'Same-day delivery available', sub: r.city ? 'We hand-deliver across ' + r.city + ' today.' : 'Same-day delivery available here.' },
    'next-day': { bg: 'rgba(184,137,58,0.12)', bd: 'rgba(184,137,58,0.45)', fg: '#8A6520', title: 'Next-day delivery by air', sub: 'Same-day isn’t available at this pin — we’ll deliver tomorrow.' },
    'none':     { bg: 'rgba(140,46,46,0.08)',  bd: 'rgba(140,46,46,0.35)', fg: '#8C2E2E', title: 'Not serviceable yet', sub: 'We don’t deliver to this pincode yet.' },
    'invalid':  { bg: 'var(--bb-cream)',       bd: 'var(--line)',          fg: 'var(--fg-2)', title: 'Enter a valid 6-digit pincode', sub: 'Serviceability is checked instantly.' }
  };
  const m = MAP[r.status] || MAP.invalid;
  return (
    <div style={{ marginTop: 10, padding: '11px 14px', background: m.bg, border: '1px solid ' + m.bd, borderRadius: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: m.fg, flex: '0 0 auto' }} />
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.18em', color: m.fg, textTransform: 'uppercase' }}>{m.title}</span>
      </div>
      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 13, color: 'var(--fg-2)' }}>{m.sub}</div>
    </div>
  );
}
window.GS_PinBanner = GS_PinBanner;

// ── founder booking form (dark panel) ────────────────────────────────────────
const FD_DELIVERY_FEE = 599;
function FounderBooking() {
  const FD_CARD  = { background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(225,200,146,0.22)', borderRadius: 18, padding: 24 };
  const FD_INPUT = { width: '100%', padding: '12px 14px', background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(225,200,146,0.28)', borderRadius: 8, color: 'var(--bb-ivory)', outline: 'none', fontFamily: 'var(--font-serif)', fontSize: 15 };
  const FD_LBL   = { display: 'block', fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.24em', color: 'var(--bb-gold-light)', marginBottom: 6 };
  const FD_QTY   = { width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,255,255,0.1)', color: 'var(--bb-gold-light)', border: '1px solid rgba(225,200,146,0.3)', cursor: 'pointer', fontSize: 17, fontFamily: 'var(--font-serif)' };

  const [boxId, setBoxId]     = React.useState('queen');
  const [qty, setQty]         = React.useState(1);
  const [note, setNote]       = React.useState('');
  const [city, setCity]       = React.useState('');
  const [date, setDate]       = React.useState('');
  const [slotId, setSlotId]   = React.useState('morning');
  const [rName, setRName]     = React.useState('');
  const [rPhone, setRPhone]   = React.useState('');
  const [email, setEmail]     = React.useState(window.BB_STORE.user?.email || '');
  const [addr, setAddr]       = React.useState('');
  const [payMethod, setPayMethod] = React.useState('upi');
  const [done, setDone]       = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendErr, setSendErr] = React.useState('');

  const FD_BOXES = [
    { id: 'petite', name: 'Petite Bliss Box',  count: '6 hand-rolled bites',         price: 949,  img: 'assets/truffles-board.jpg', tag: 'SIGNATURE' },
    { id: 'queen',  name: 'The Queen Box',     count: '12 assorted · velvet',   price: 1799, img: 'assets/box-assorted.jpg',   tag: 'MOST LOVED' },
    { id: 'royal',  name: 'Royal Almond Tray', count: '24 pieces · gold seal',  price: 2799, img: 'assets/duet-split.jpg',     tag: 'PREMIUM' },
    { id: 'duet',   name: 'Cocoa Duet Bars',   count: '3 loaded bars',               price: 1399, img: 'assets/bars-duo.jpg',       tag: 'ARTISAN' },
  ];

  const box   = FD_BOXES.find(b => b.id === boxId);
  const slot  = GS_FD_SLOTS.find(s => s.id === slotId);
  const total = box.price * qty + FD_DELIVERY_FEE;
  const canSend = city && date && rName.trim() && addr.trim();

  const send = async () => {
    setSending(true); setSendErr('');
    try {
      const res = await fetch('/api/order', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ founderDelivery: true, box: box.name, qty, note, recipient: { name: rName, phone: rPhone }, customerEmail: email, city, date, slot: { label: slot.label, range: slot.range }, address: addr, paymentMethod: payMethod, total }),
      });
      if (!res.ok) throw new Error('Server error');
      setDone(true);
      setTimeout(() => setDone(false), 7000);
      window.BB_STORE.notify('Booking confirmed! The founder will WhatsApp you shortly.', 'success');
    } catch { setSendErr('Could not book — please WhatsApp us directly.'); }
    finally { setSending(false); }
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.1fr) minmax(0,0.9fr)', gap: 24, alignItems: 'start' }} className="bb-fd-grid">
      {/* LEFT */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={FD_CARD}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 16 }}>STEP 1 — CHOOSE YOUR BOX</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="bb-fd-boxes">
            {FD_BOXES.map(b => {
              const active = b.id === boxId;
              return (
                <button key={b.id} onClick={() => setBoxId(b.id)} style={{ display: 'flex', gap: 12, alignItems: 'center', textAlign: 'left', padding: 10, borderRadius: 12, cursor: 'pointer', background: active ? 'rgba(225,200,146,0.14)' : 'rgba(255,255,255,0.05)', border: active ? '1.5px solid var(--bb-gold)' : '1px solid rgba(225,200,146,0.18)', boxShadow: active ? '0 0 0 3px rgba(225,200,146,0.08)' : 'none', transition: 'all 200ms' }}>
                  <img src={b.img} alt={b.name} style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8, flex: '0 0 auto' }} />
                  <span>
                    <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 8, letterSpacing: '0.2em', color: 'var(--bb-gold-light)' }}>{b.tag}</span>
                    <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-ivory)', lineHeight: 1.15 }}>{b.name}</span>
                    <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-gold)' }}>&#8377;{b.price.toLocaleString('en-IN')}</span>
                  </span>
                </button>
              );
            })}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, padding: '8px 14px', background: 'rgba(255,255,255,0.04)', borderRadius: 10, border: '1px solid rgba(225,200,146,0.15)' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.2em', color: 'var(--bb-gold-light)' }}>QUANTITY</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <button onClick={() => setQty(q => Math.max(1, q - 1))} style={FD_QTY}>&#x2212;</button>
              <span style={{ fontFamily: 'var(--font-serif)', fontSize: 22, color: 'var(--bb-ivory)', minWidth: 22, textAlign: 'center' }}>{qty}</span>
              <button onClick={() => setQty(q => Math.min(20, q + 1))} style={FD_QTY}>+</button>
            </div>
          </div>
        </div>

        <div style={FD_CARD}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 14 }}>STEP 2 — YOUR PERSONAL NOTE</div>
          <textarea value={note} onChange={e => setNote(e.target.value)} maxLength={280}
            placeholder="A message for the recipient…"
            style={{ ...FD_INPUT, resize: 'vertical', minHeight: 90, lineHeight: 1.6, fontFamily: 'var(--font-script)', fontSize: 22, color: 'var(--bb-gold-light)' }} />
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 6 }}>
            <span style={{ fontFamily: 'var(--font-serif)', fontSize: 12, color: 'rgba(225,200,146,0.45)' }}>{note.length}/280</span>
          </div>
        </div>

        {/* Inclusions */}
        <div style={{ ...FD_CARD, padding: '18px 22px' }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 14 }}>WHAT’S INCLUDED</div>
          {[
            ['Founder delivers to the door in person', 'No courier, no drop-off.'],
            ['Ribbon-tied unboxing in front of them',  'Presented, not just handed over.'],
            ['Handwritten card in your exact words',   'Penned by us, sealed before we leave.'],
            ['Live WhatsApp updates',                  'From kitchen to doorstep.'],
            ['Founder’s signature on the lid',    'A keepsake in itself.'],
          ].map(([t, s]) => (
            <div key={t} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 12 }}>
              <span style={{ color: 'var(--bb-gold)', fontSize: 12, flex: '0 0 auto', marginTop: 2 }}>&#10022;</span>
              <div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-ivory)', lineHeight: 1.3 }}>{t}</div>
                <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'rgba(250,246,236,0.48)', marginTop: 2 }}>{s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* RIGHT */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={FD_CARD}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 16 }}>STEP 3 — BOOKING DETAILS</div>
          <div style={{ marginBottom: 16 }}>
            <span style={FD_LBL}>DELIVERY CITY</span>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {GS_FD_CITIES.map(c => (
                <button key={c} onClick={() => setCity(c)} style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.16em', padding: '8px 16px', borderRadius: 999, cursor: 'pointer', border: city === c ? '1px solid var(--bb-gold)' : '1px solid rgba(225,200,146,0.28)', background: city === c ? 'rgba(225,200,146,0.18)' : 'transparent', color: city === c ? 'var(--bb-gold-light)' : 'rgba(250,246,236,0.6)', transition: 'all 200ms' }}>{c}</button>
              ))}
            </div>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'block' }}>
              <span style={FD_LBL}>PREFERRED DATE</span>
              <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{ ...FD_INPUT, colorScheme: 'dark' }} />
            </label>
          </div>
          <div style={{ marginBottom: 16 }}>
            <span style={FD_LBL}>ARRIVAL WINDOW</span>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {GS_FD_SLOTS.map(s => {
                const active = slotId === s.id;
                return (
                  <button key={s.id} onClick={() => setSlotId(s.id)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', borderRadius: 10, cursor: 'pointer', background: active ? 'rgba(225,200,146,0.14)' : 'rgba(255,255,255,0.04)', border: active ? '1.5px solid var(--bb-gold)' : '1px solid rgba(225,200,146,0.15)', transition: 'all 200ms' }}>
                    <span style={{ fontFamily: 'var(--font-serif)', fontSize: 15, color: active ? 'var(--bb-ivory)' : 'rgba(250,246,236,0.65)' }}>{s.label}</span>
                    <span style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.14em', color: 'var(--bb-gold-light)' }}>{s.range}</span>
                  </button>
                );
              })}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
            <label style={{ display: 'block' }}>
              <span style={FD_LBL}>RECIPIENT NAME</span>
              <input value={rName} onChange={e => setRName(e.target.value)} placeholder="Aanya Mehta" style={FD_INPUT} />
            </label>
            <label style={{ display: 'block' }}>
              <span style={FD_LBL}>MOBILE</span>
              <input value={rPhone} onChange={e => setRPhone(e.target.value)} placeholder="+91 …" type="tel" style={FD_INPUT} />
            </label>
          </div>
          <label style={{ display: 'block', marginBottom: 14 }}>
            <span style={FD_LBL}>EMAIL (optional — for order updates)</span>
            <input value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" type="email" style={FD_INPUT} />
          </label>
          <label style={{ display: 'block' }}>
            <span style={FD_LBL}>FULL DELIVERY ADDRESS</span>
            <textarea value={addr} onChange={e => setAddr(e.target.value)} placeholder="Flat / house no., building, street, area, city, pincode…" style={{ ...FD_INPUT, resize: 'vertical', minHeight: 78, lineHeight: 1.5 }} />
          </label>
        </div>

        {/* Payment method */}
        <div style={FD_CARD}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 14 }}>PAYMENT METHOD</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            {[{ k: 'upi', label: 'Pay via UPI' }, { k: 'cod', label: 'Cash on Delivery' }].map(p => (
              <button key={p.k} onClick={() => setPayMethod(p.k)} style={{
                flex: 1, fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.14em', padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                border: payMethod === p.k ? '1px solid var(--bb-gold)' : '1px solid rgba(225,200,146,0.28)',
                background: payMethod === p.k ? 'rgba(225,200,146,0.18)' : 'transparent',
                color: payMethod === p.k ? 'var(--bb-gold-light)' : 'rgba(250,246,236,0.6)', transition: 'all 200ms'
              }}>{p.label}</button>
            ))}
          </div>
          {payMethod === 'upi' && <UpiQr amount={total} note={`Blissful Bites founder delivery — ${rName || 'gift'}`} />}
          {payMethod === 'cod' && (
            <div style={{ padding: '12px 14px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(225,200,146,0.18)', borderRadius: 10, fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, color: 'rgba(250,246,236,0.65)' }}>
              Pay the founder in cash on arrival.
            </div>
          )}
        </div>

        {/* Summary & CTA */}
        <div style={{ background: 'rgba(225,200,146,0.08)', border: '1.5px solid rgba(225,200,146,0.28)', borderRadius: 18, padding: 24 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-light)', marginBottom: 16 }}>ORDER SUMMARY</div>
          {[
            [box.name + ' × ' + qty, '&#8377;' + (box.price * qty).toLocaleString('en-IN')],
            ['Founder’s personal delivery', '&#8377;' + FD_DELIVERY_FEE.toLocaleString('en-IN')],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-ivory)' }}>
              <span>{k}</span><span dangerouslySetInnerHTML={{ __html: v }} />
            </div>
          ))}
          {city && <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontFamily: 'var(--font-serif)', fontSize: 13, color: 'rgba(225,200,146,0.55)', fontStyle: 'italic' }}><span>City</span><span>{city}</span></div>}
          {date && <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontFamily: 'var(--font-serif)', fontSize: 13, color: 'rgba(225,200,146,0.55)', fontStyle: 'italic' }}><span>Date</span><span>{new Date(date + 'T00:00:00').toLocaleDateString('en-IN', { day: 'numeric', month: 'long' })}</span></div>}
          <div style={{ height: 1, background: 'rgba(225,200,146,0.22)', margin: '12px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.2em', color: 'var(--bb-gold-light)' }}>TOTAL</span>
            <span style={{ fontFamily: 'var(--font-serif)', fontSize: 30, color: 'var(--bb-ivory)' }}>&#8377;{total.toLocaleString('en-IN')}</span>
          </div>
          <button className="btn btn-foil" onClick={send} disabled={!canSend || sending}
            style={{ width: '100%', padding: '15px 24px', opacity: (canSend && !sending) ? 1 : 0.52, cursor: (canSend && !sending) ? 'pointer' : 'not-allowed' }}>
            {done ? 'Booking Confirmed ✓' : sending ? 'Booking…' : payMethod === 'upi' ? "I've Paid — Book Delivery →" : 'Book Founder Delivery (COD) →'}
          </button>
          {sendErr && <div style={{ marginTop: 8, padding: '10px 14px', background: 'rgba(140,46,46,0.2)', border: '1px solid rgba(200,100,100,0.4)', borderRadius: 8, color: '#F5A0A0', fontFamily: 'var(--font-serif)', fontSize: 13 }}>{sendErr}</div>}
          {done && <div style={{ marginTop: 10, padding: '12px 16px', background: 'rgba(79,107,58,0.18)', border: '1px solid rgba(79,107,58,0.42)', borderRadius: 10, color: '#9AD67E', fontFamily: 'var(--font-serif)', fontSize: 14 }}>Booking received. The founder will WhatsApp you within the hour to confirm.</div>}
          {!canSend && !done && <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'rgba(225,200,146,0.42)', textAlign: 'center', marginTop: 10 }}>
            {!city ? 'Select a city to continue.' : !date ? 'Choose a preferred date.' : 'Add recipient details and full address.'}
          </div>}
        </div>
      </div>

      <style>{`
        @media (max-width: 860px) { .bb-fd-grid { grid-template-columns: 1fr !important; } .bb-fd-boxes { grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 480px) { .bb-fd-boxes { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

// ── main component ────────────────────────────────────────────────────────────
function GiftShop() {
  const [tab, setTab]         = React.useState('express'); // 'express' | 'founder'
  const [cartCount, setCartCount] = React.useState(window.BB_STORE.cartCount());
  const [wlCount, setWlCount] = React.useState(window.BB_STORE.wishlistCount());

  React.useEffect(() => {
    const onCart = () => setCartCount(window.BB_STORE.cartCount());
    const onWish = () => setWlCount(window.BB_STORE.wishlistCount());
    window.addEventListener('bb-cart-update', onCart);
    window.addEventListener('bb-wishlist-update', onWish);
    return () => {
      window.removeEventListener('bb-cart-update', onCart);
      window.removeEventListener('bb-wishlist-update', onWish);
    };
  }, []);

  const boxes = GS_BOXES.map(def => {
    const cmsBoxes = (window.BB_CONTENT || {}).sameDayBoxes;
    if (!Array.isArray(cmsBoxes) || cmsBoxes.length !== GS_BOXES.length) return def;
    const ov = cmsBoxes[GS_BOXES.indexOf(def)] || {};
    return { ...def, ...ov, price: ov.price !== undefined ? Number(ov.price) : def.price };
  });

  return (
    <section id="same-day" style={{ background: tab === 'founder' ? 'var(--bb-burgundy-deep)' : 'var(--bb-ivory)', padding: 'var(--s-9) 32px var(--s-7)', transition: 'background 500ms ease' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>

        {/* ── Section Header ── */}
        <div className="bb-reveal" style={{ textAlign: 'center', marginBottom: 'var(--s-6)' }}>
          <div className="bb-eyebrow" style={{ color: tab === 'founder' ? 'var(--bb-gold-light)' : undefined }}>
            &#9733; SAME-DAY GIFTING &amp; FOUNDER DELIVERY
          </div>
          <h2 style={{ marginTop: 14, fontSize: 'clamp(32px, 4vw, 54px)', lineHeight: 1.06, color: tab === 'founder' ? 'var(--bb-ivory)' : undefined }}>
            {tab === 'express' ? <>Don&apos;t send flowers.<br /><span style={{ fontFamily: 'var(--font-script)', fontSize: '1.38em', color: 'var(--bb-gold-deep)', letterSpacing: 0, fontWeight: 400, lineHeight: 0.85 }}>Send something they&apos;ll remember.</span></> : <>Delivered by the Founder.<br /><span style={{ fontFamily: 'var(--font-script)', fontSize: '1.38em', color: 'var(--bb-gold)', letterSpacing: 0, fontWeight: 400, lineHeight: 0.85 }}>Personally.</span></>}
          </h2>
          <p style={{ fontFamily: 'var(--font-serif)', fontSize: 17, lineHeight: 1.65, color: tab === 'founder' ? 'rgba(250,246,236,0.72)' : 'var(--fg-2)', maxWidth: 560, margin: '14px auto 0', fontStyle: 'italic' }}>
            {tab === 'express'
              ? 'A velvet-lined box, ribbon-tied, on their desk before tea — with a handwritten note in your words.'
              : 'Not a courier. Not a rider. The founder of Blissful Bites arrives at the door — box in hand, ribbon tied, story ready to tell.'}
          </p>
        </div>

        {/* ── Tab Toggle ── */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 'var(--s-6)' }}>
          <div style={{ display: 'inline-flex', background: tab === 'founder' ? 'rgba(255,255,255,0.08)' : 'var(--bb-pearl)', borderRadius: 999, padding: 4, border: tab === 'founder' ? '1px solid rgba(225,200,146,0.28)' : '1px solid var(--line)', gap: 4, boxShadow: 'var(--shadow-1)' }}>
            {[
              { key: 'express', label: '&#9654; Express Gift', sub: 'Add to cart · same-day' },
              { key: 'founder', label: '&#10022; Founder’s Touch', sub: 'Personal delivery · book a slot' },
            ].map(t => {
              const active = tab === t.key;
              const isDark = tab === 'founder';
              return (
                <button key={t.key} onClick={() => setTab(t.key)} style={{
                  padding: '11px 28px', borderRadius: 999, border: 'none', cursor: 'pointer', transition: 'all 260ms',
                  background: active ? (isDark ? 'var(--bb-burgundy)' : 'var(--bb-burgundy)') : 'transparent',
                  boxShadow: active ? '0 3px 12px rgba(91,31,46,0.35)' : 'none',
                  textAlign: 'center',
                }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, letterSpacing: '0.18em', color: active ? 'var(--bb-gold-light)' : (isDark ? 'rgba(250,246,236,0.55)' : 'var(--fg-2)'), marginBottom: 2 }} dangerouslySetInnerHTML={{ __html: t.label }} />
                  <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 11.5, color: active ? 'rgba(225,200,146,0.72)' : (isDark ? 'rgba(250,246,236,0.35)' : 'var(--fg-3)') }}>{t.sub}</div>
                </button>
              );
            })}
          </div>
        </div>

        {/* ── Express: product grid ── */}
        {tab === 'express' && (
          <>
            {/* Trust badges */}
            <div className="bb-reveal" style={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 10, marginBottom: 32 }}>
              {['HAND-DELIVERED', 'RIBBON-TIED', 'UNDER 4 HOURS', 'FREE SAME-DAY SLOT'].map(b => (
                <span key={b} style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.22em', color: 'var(--bb-gold-deep)', padding: '7px 16px', borderRadius: 999, border: '1px solid var(--line-gold)', background: 'var(--bb-cream)' }}>{b}</span>
              ))}
            </div>

            {/* Cart CTA banner */}
            {cartCount > 0 && (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 22px', background: 'var(--bb-burgundy)', borderRadius: 14, marginBottom: 28, border: '1px solid rgba(225,200,146,0.3)' }}>
                <span style={{ fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-ivory)' }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--bb-gold-light)', marginRight: 10 }}>YOUR CART</span>
                  {cartCount} item{cartCount !== 1 ? 's' : ''} ready to send
                </span>
                <button className="btn btn-foil" onClick={() => window.BB_STORE.openCart()} style={{ padding: '10px 22px' }}>View Cart &amp; Checkout &#8594;</button>
              </div>
            )}

            {/* Product cards 2x2 */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }} className="bb-gs-grid">
              {boxes.map(box => <GS_ProductCard key={box.id} box={box} />)}
            </div>

            {/* Addons strip */}
            <div className="bb-reveal" style={{ marginTop: 32, padding: '22px 28px', background: 'var(--bb-cream)', borderRadius: 16, border: '1px solid var(--line-gold)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.24em', color: 'var(--bb-gold-deep)', marginBottom: 14 }}>POPULAR ADD-ONS — SELECTED IN CART AT CHECKOUT</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                {GS_ADDONS.map(a => (
                  <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', background: 'var(--bb-pearl)', borderRadius: 10, border: '1px solid var(--line)' }}>
                    <span style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-burgundy-deep)' }}>{a.name}</span>
                    <span style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.14em', color: 'var(--bb-gold-deep)', background: 'var(--bb-cream)', padding: '3px 9px', borderRadius: 999, border: '1px solid var(--line-gold)' }}>+&#8377;{a.price}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Cities */}
            <div className="bb-reveal" style={{ marginTop: 28, paddingTop: 20, borderTop: '1px solid var(--line-gold)' }}>
              <div className="bb-eyebrow" style={{ marginBottom: 10 }}>SAME-DAY DELIVERY CITIES</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {['Mumbai', 'Delhi NCR', 'Bengaluru', 'Hyderabad', 'Pune', 'Chennai', 'Kolkata', 'Ahmedabad', 'Jaipur'].map(c => (
                  <span key={c} style={{ fontFamily: 'var(--font-ui)', fontSize: 12, padding: '5px 13px', borderRadius: 999, background: 'var(--bb-pearl)', border: '1px solid var(--line)', color: 'var(--fg-2)' }}>{c}</span>
                ))}
                <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-3)', alignSelf: 'center', marginLeft: 4 }}>Other pincodes — next-day by air.</span>
              </div>
            </div>
          </>
        )}

        {/* ── Founder tab ── */}
        {tab === 'founder' && (
          <>
            <div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 10, marginBottom: 36, color: 'var(--bb-gold-light)', fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.22em' }}>
              <span>MUMBAI · DELHI · BENGALURU</span>
              <span style={{ opacity: 0.35 }}>·</span>
              <span>APPOINTMENT ONLY</span>
              <span style={{ opacity: 0.35 }}>·</span>
              <span>SAME OR NEXT DAY</span>
            </div>
            <FounderBooking />
          </>
        )}
      </div>

      <style>{`
        @media (max-width: 1100px) { .bb-gs-grid { grid-template-columns: repeat(2, 1fr) !important; } }
        @media (max-width: 560px)  { .bb-gs-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

window.GiftShop = GiftShop;
