// SameDay.jsx — same-day chocolate gifting (clean, light, FNP-style flow)
const SD_BOX_DEFAULTS = [
  { 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 \u00b7 velvet-lined', price: 1199, img: 'assets/box-assorted.jpg',   tag: 'CLASSIC' },
  { id: 'royal',  name: 'Royal Almond Tray', count: '24 pieces \u00b7 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 SD_ADDON_DEFAULTS = [
  { 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.' }
];
function sdMerge(defaults, cmsArr) {
  if (!Array.isArray(cmsArr) || cmsArr.length !== defaults.length) return defaults;
  return defaults.map((def, i) => {
    const ov = cmsArr[i] || {};
    return { ...def, ...ov, price: ov.price !== undefined ? Number(ov.price) : def.price };
  });
}
const SD = {
  OCCASIONS: [
    { key: 'thanks',   label: 'Thank you',       script: 'Couldn\u2019t have done it without you.' },
    { key: 'congrats', label: 'Congratulations', script: 'Onward, upward, well-earned.' },
    { key: 'birthday', label: 'Happy Birthday',  script: 'Many, many more.' },
    { key: 'welcome',  label: 'Welcome',         script: 'Glad to have you with us.' },
    { key: 'sorry',    label: 'Sorry',           script: 'I owe you one.' },
    { key: 'because',  label: 'Just because',    script: 'Thinking of you.' }
  ],
  get BOXES()  { return sdMerge(SD_BOX_DEFAULTS,  (window.BB_CONTENT || {}).sameDayBoxes);  },
  get ADDONS() { return sdMerge(SD_ADDON_DEFAULTS, (window.BB_CONTENT || {}).sameDayAddons); },
  CITIES: ['Mumbai', 'Delhi NCR', 'Bengaluru', 'Hyderabad', 'Pune', 'Chennai', 'Kolkata', 'Ahmedabad', 'Jaipur'],
  SLOTS: [
    { id: 'today-eve', when: 'Today',    range: '5 PM \u2013 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 \u2013 12 PM',   fee: 0,   tag: 'MORNING',  cutoffH: 99 },
    { id: 'tom-pm',    when: 'Tomorrow', range: '4 PM \u2013 8 PM',    fee: 0,   tag: 'EVENING',  cutoffH: 99 }
  ]
};

// ---- pincode serviceability: same-day metros · next-day by air · not serviceable ----
const SD_SAME_DAY = {
  '400': 'Mumbai', '401': 'Mumbai', '410': 'Navi Mumbai',
  '110': 'Delhi NCR', '201': 'Noida & Ghaziabad', '122': 'Gurugram',
  '560': 'Bengaluru', '500': 'Hyderabad', '411': 'Pune',
  '600': 'Chennai', '700': 'Kolkata', '380': 'Ahmedabad', '302': 'Jaipur'
};
// remote regions we don't deliver to yet (J&K, NE hills, islands)
const SD_NO_SERVICE = ['190', '191', '192', '193', '194', '737', '738', '744', '796', '797', '798', '799'];
function sdCheckPin(pin) {
  if (!/^\d{6}$/.test(pin)) return { status: 'invalid' };
  const p3 = pin.slice(0, 3);
  if (SD_NO_SERVICE.includes(p3)) return { status: 'none' };
  if (SD_SAME_DAY[p3]) return { status: 'same-day', city: SD_SAME_DAY[p3] };
  return { status: 'next-day' };
}

function SameDay() {
  const [occ, setOcc]   = React.useState(SD.OCCASIONS[0]);
  const [note, setNote] = React.useState('');
  const [hand, setHand] = React.useState(true);
  const [boxId, setBoxId]   = React.useState('queen');
  const [qty, setQty]       = React.useState(1);
  const [addons, setAddons] = React.useState({ wrap: true, monogram: false, rose: false, card: false });
  const [slotId, setSlotId] = React.useState('today-eve');
  const [city, setCity]     = React.useState('');
  const [rName, setRName]   = React.useState('');
  const [rPhone, setRPhone] = React.useState('');
  const [pincode, setPincode]   = React.useState('');
  const [pinResult, setPinResult] = React.useState(null); // null | { status, city? }
  const [addr, setAddr]     = React.useState({ flat: '', street: '', area: '' });
  const [geo, setGeo]       = React.useState(null);       // null | { state, lat?, lng? }
  const [done, setDone]     = React.useState(false);

  const serviceable = !!pinResult && (pinResult.status === 'same-day' || pinResult.status === 'next-day');
  const sameDayOk   = !!pinResult && pinResult.status === 'same-day';
  const canSend     = serviceable && rName.trim() && addr.flat.trim();

  const checkPin = (val) => {
    const r = sdCheckPin(val);
    setPinResult(r);
    if (r.status === 'same-day') setCity(r.city);
  };
  const onPin = (e) => {
    const v = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
    setPincode(v);
    if (v.length === 6) checkPin(v); else setPinResult(null);
  };
  const detect = () => {
    if (!navigator.geolocation) { setGeo({ state: 'unsupported' }); return; }
    setGeo({ state: 'locating' });
    navigator.geolocation.getCurrentPosition(
      (pos) => setGeo({ state: 'ok', lat: pos.coords.latitude.toFixed(4), lng: pos.coords.longitude.toFixed(4) }),
      () => setGeo({ state: 'denied' })
    );
  };

  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => { const t = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(t); }, []);
  const pad = (n) => String(n).padStart(2, '0');
  const currentHour = now.getHours() + now.getMinutes() / 60;

  // when serviceability changes, pre-select a sensible delivery window
  React.useEffect(() => {
    if (!pinResult) return;
    if (pinResult.status === 'same-day') {
      const firstToday = SD.SLOTS.find((s) => s.when === 'Today' && currentHour < s.cutoffH);
      setSlotId(firstToday ? firstToday.id : 'tom-am');
    } else if (pinResult.status === 'next-day') {
      setSlotId('tom-am');
    }
  }, [pinResult]); // eslint-disable-line

  const box = SD.BOXES.find((b) => b.id === boxId);
  const slot = SD.SLOTS.find((s) => s.id === slotId);
  const addonTotal = SD.ADDONS.filter((a) => addons[a.id]).reduce((s, a) => s + a.price, 0);
  const itemTotal  = box.price * qty;
  const total      = itemTotal + addonTotal + slot.fee;
  const message    = note || occ.script;

  const cutoff = new Date(now); cutoff.setHours(16, 0, 0, 0);
  const inWindow = now < cutoff;
  const diffMs = Math.max(0, cutoff - now);
  const hh = Math.floor(diffMs / 3600000), mm = Math.floor((diffMs % 3600000) / 60000), ss = Math.floor((diffMs % 60000) / 1000);

  const [sending, setSending] = React.useState(false);
  const [sendErr, setSendErr] = React.useState('');
  const send = async () => {
    setSending(true);
    setSendErr('');
    try {
      const payload = {
        box:      box.name,
        qty,
        addons,
        note:     message,
        occasion: occ.label,
        noteStyle: hand ? 'handwritten' : 'printed',
        recipient: { name: rName, phone: rPhone },
        pincode,
        address:  addr,
        city,
        slot:     { when: slot.when, range: slot.range, tag: slot.tag },
        total,
      };
      const res = await fetch('http://localhost:3001/api/order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error('Server error');
      setDone(true);
      setTimeout(() => setDone(false), 5000);
    } catch {
      setSendErr('Could not place order — please WhatsApp us directly.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="same-day" style={{ background: 'var(--bb-cream)', padding: 'var(--s-9) 32px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        {/* heading */}
        <div className="bb-reveal" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,0.95fr)', gap: 'var(--s-7)', alignItems: 'end', marginBottom: 'var(--s-7)' }}>
          <div>
            <div className="bb-eyebrow">★ SAME-DAY GIFTING</div>
            <h2 style={{ marginTop: 14, fontSize: 'clamp(34px, 4.4vw, 60px)', lineHeight: 1.02 }}>
              Don't send flowers.<br />
              <span style={{ fontFamily: 'var(--font-script)', fontSize: '1.4em', color: 'var(--bb-gold-deep)', letterSpacing: 0, fontWeight: 400, lineHeight: 0.85 }}>Send something they'll remember.</span>
            </h2>
          </div>
          <div>
            <p className="lede" style={{ marginBottom: 14, marginTop: 0 }}>
              A velvet-lined box of dryfruit-loaded chocolates, ribbon-tied, on their desk before tea — with a handwritten note in your words.
            </p>
            <div style={{ display: 'flex', gap: 10, color: 'var(--bb-gold-deep)', fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.22em', flexWrap: 'wrap' }}>
              <span>HAND-DELIVERED</span><span style={{ opacity: 0.4 }}>·</span>
              <span>RIBBON-TIED</span><span style={{ opacity: 0.4 }}>·</span>
              <span>UNDER 4 HOURS</span>
            </div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.45fr) minmax(0,1fr)', gap: 22, alignItems: 'start' }} className="bb-sd-grid">

          {/* LEFT — build the gift */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* boxes */}
            <div style={SD_CARD}>
              <SDStep n="1" label="CHOOSE THE BOX" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="bb-sd-boxes">
                {SD.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 ? 'var(--bb-cream)' : 'var(--bb-pearl)',
                      border: active ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)',
                      boxShadow: active ? 'var(--shadow-1)' : 'none', transition: 'all 200ms'
                    }}>
                      <img src={b.img} alt={b.name} style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 8, flex: '0 0 auto' }} />
                      <span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.2em', color: 'var(--bb-gold-deep)' }}>{b.tag}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 17, color: 'var(--bb-burgundy-deep)', lineHeight: 1.1 }}>{b.name}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-burgundy-deep)' }}>₹{b.price.toLocaleString('en-IN')}</span>
                      </span>
                    </button>
                  );
                })}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, padding: '8px 14px', background: 'var(--bb-cream)', borderRadius: 10, border: '1px solid var(--line)' }}>
                <span className="meta" style={{ letterSpacing: '0.16em' }}>QUANTITY</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <button onClick={() => setQty((q) => Math.max(1, q - 1))} style={SD_QTY}>−</button>
                  <span style={{ fontFamily: 'var(--font-serif)', fontSize: 22, color: 'var(--bb-burgundy-deep)', minWidth: 22, textAlign: 'center' }}>{qty}</span>
                  <button onClick={() => setQty((q) => Math.min(99, q + 1))} style={SD_QTY}>+</button>
                </div>
              </div>
            </div>

            {/* note */}
            <div style={SD_CARD}>
              <SDStep n="2" label="WRITE THE NOTE" />
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
                {SD.OCCASIONS.map((o) => {
                  const active = o.key === occ.key;
                  return (
                    <button key={o.key} onClick={() => { setOcc(o); setNote(''); }} style={{
                      fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
                      padding: '8px 13px', borderRadius: 999, cursor: 'pointer',
                      border: active ? '1px solid var(--bb-burgundy)' : '1px solid var(--line-strong)',
                      background: active ? 'var(--bb-burgundy)' : 'transparent',
                      color: active ? 'var(--bb-ivory)' : 'var(--bb-cocoa)', transition: 'all 200ms'
                    }}>{o.label}</button>
                  );
                })}
              </div>
              <div style={{ background: 'var(--bb-cream)', borderRadius: 14, padding: '18px 20px', position: 'relative', border: '1px solid var(--line-gold)' }}>
                <div aria-hidden="true" style={{ position: 'absolute', top: 12, right: 16, fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.3em', color: 'var(--bb-gold-deep)' }}>✦ BLISSFUL BITES ✦</div>
                <textarea value={note} onChange={(e) => setNote(e.target.value)} maxLength={200} placeholder={occ.script + '\u2026'}
                  style={{
                    width: '100%', minHeight: 84, border: 'none', outline: 'none', background: 'transparent', resize: 'none', marginTop: 12,
                    fontFamily: hand ? 'var(--font-script)' : 'var(--font-serif)',
                    fontSize: hand ? 34 : 18, lineHeight: hand ? 1.05 : 1.45,
                    color: 'var(--bb-burgundy-deep)', fontStyle: hand ? 'normal' : 'italic'
                  }} />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, paddingTop: 12, borderTop: '1px dashed var(--line-gold)' }}>
                  <div style={{ display: 'inline-flex', background: 'var(--bb-pearl)', borderRadius: 999, padding: 3, border: '1px solid var(--line)' }}>
                    {[{ k: true, label: 'Handwritten' }, { k: false, label: 'Printed' }].map((opt) => (
                      <button key={String(opt.k)} onClick={() => setHand(opt.k)} style={{
                        fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.18em',
                        padding: '6px 12px', borderRadius: 999, cursor: 'pointer', border: 'none',
                        background: hand === opt.k ? 'var(--bb-burgundy)' : 'transparent',
                        color: hand === opt.k ? 'var(--bb-ivory)' : 'var(--bb-cocoa)'
                      }}>{opt.label.toUpperCase()}</button>
                    ))}
                  </div>
                  <span className="meta">{message.length}/200</span>
                </div>
              </div>
              <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-3)', marginTop: 10 }}>
                Penned by our calligrapher in burgundy ink, slipped into the lid.
              </div>
            </div>

            {/* addons */}
            <div style={SD_CARD}>
              <SDStep n="3" label="ADD A LITTLE EXTRA" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }} className="bb-sd-addons">
                {SD.ADDONS.map((a) => {
                  const on = addons[a.id];
                  return (
                    <label key={a.id} style={{
                      display: 'flex', gap: 11, alignItems: 'center', padding: '11px 13px', borderRadius: 10, cursor: 'pointer',
                      background: on ? 'var(--bb-cream)' : 'var(--bb-pearl)',
                      border: on ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)', transition: 'all 200ms'
                    }}>
                      <span style={{ width: 20, height: 20, borderRadius: 5, border: '1.5px solid var(--bb-gold-deep)', background: on ? 'var(--bb-burgundy)' : 'transparent', display: 'grid', placeItems: 'center', flex: '0 0 auto' }}>
                        {on && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--bb-gold-light)" strokeWidth="3"><path d="M5 12l5 5L20 7" /></svg>}
                      </span>
                      <input type="checkbox" checked={on} onChange={() => setAddons((x) => ({ ...x, [a.id]: !x[a.id] }))} style={{ display: 'none' }} />
                      <span style={{ flex: 1 }}>
                        <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-burgundy-deep)', lineHeight: 1.1 }}>{a.name}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-3)' }}>{a.desc}</span>
                      </span>
                      <span style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-gold-deep)' }}>+₹{a.price}</span>
                    </label>
                  );
                })}
              </div>
            </div>
          </div>

          {/* RIGHT — delivery + summary (sticky) */}
          <div style={{ position: 'sticky', top: 80, display: 'flex', flexDirection: 'column', gap: 18 }} className="bb-sd-summary">
            <div style={SD_CARD}>
              <SDStep n="4" label="RECIPIENT & ADDRESS" />

              {/* recipient */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
                <label style={{ display: 'block' }}>
                  <span style={SD_LBL}>RECIPIENT NAME</span>
                  <input value={rName} onChange={(e) => setRName(e.target.value)} placeholder="Aanya Mehta" style={SD_INPUT} />
                </label>
                <label style={{ display: 'block' }}>
                  <span style={SD_LBL}>MOBILE</span>
                  <input value={rPhone} onChange={(e) => setRPhone(e.target.value)} placeholder="+91 …" type="tel" style={SD_INPUT} />
                </label>
              </div>

              {/* map + detect location */}
              <SDMap geo={geo} onDetect={detect} />

              {/* pincode serviceability check */}
              <span style={{ ...SD_LBL, display: 'block', marginTop: 14 }}>DELIVERY PINCODE</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <input value={pincode} onChange={onPin} inputMode="numeric" placeholder="6-digit pincode"
                  style={{ ...SD_INPUT, flex: 1, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.14em' }} />
                <button onClick={() => checkPin(pincode)} disabled={pincode.length !== 6} style={{
                  fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em', padding: '0 18px', borderRadius: 8,
                  cursor: pincode.length === 6 ? 'pointer' : 'not-allowed', background: 'var(--bb-burgundy)', color: 'var(--bb-ivory)',
                  border: 'none', opacity: pincode.length === 6 ? 1 : 0.5
                }}>CHECK</button>
              </div>
              {pinResult && <SDPinBanner r={pinResult} />}

              {/* address — revealed once serviceable */}
              {serviceable && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
                  <label style={{ display: 'block' }}>
                    <span style={SD_LBL}>FLAT / HOUSE NO.</span>
                    <input value={addr.flat} onChange={(e) => setAddr((a) => ({ ...a, flat: e.target.value }))} placeholder="Flat 14B, Acacia Tower" style={SD_INPUT} />
                  </label>
                  <label style={{ display: 'block' }}>
                    <span style={SD_LBL}>BUILDING & STREET</span>
                    <input value={addr.street} onChange={(e) => setAddr((a) => ({ ...a, street: e.target.value }))} placeholder="Hill Road, Bandra West" style={SD_INPUT} />
                  </label>
                  <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.8fr', gap: 10 }}>
                    <label style={{ display: 'block' }}>
                      <span style={SD_LBL}>AREA / LANDMARK</span>
                      <input value={addr.area} onChange={(e) => setAddr((a) => ({ ...a, area: e.target.value }))} placeholder="Near Mehboob Studio" style={SD_INPUT} />
                    </label>
                    <label style={{ display: 'block' }}>
                      <span style={SD_LBL}>CITY</span>
                      <input value={city} onChange={(e) => setCity(e.target.value)} placeholder="City" style={SD_INPUT} />
                    </label>
                  </div>
                </div>
              )}
            </div>

            {/* delivery window — gated by serviceability */}
            <div style={SD_CARD}>
              <SDStep n="5" label="DELIVERY WINDOW" />
              {!serviceable && (
                <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 14, color: 'var(--fg-3)', marginBottom: 14 }}>
                  Confirm a serviceable pincode above to see available windows.
                </div>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14, opacity: serviceable ? 1 : 0.55 }}>
                {SD.SLOTS.map((s) => {
                  const disabled = !serviceable || (s.when === 'Today' && (!sameDayOk || currentHour >= s.cutoffH));
                  const active = s.id === slotId && !disabled;
                  return (
                    <button key={s.id} disabled={disabled} onClick={() => setSlotId(s.id)} style={{
                      display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 11, alignItems: 'center',
                      padding: '10px 13px', borderRadius: 10, cursor: disabled ? 'not-allowed' : 'pointer', textAlign: 'left',
                      background: active ? 'var(--bb-cream)' : 'var(--bb-pearl)',
                      border: active ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)',
                      opacity: disabled ? 0.45 : 1, transition: 'all 200ms'
                    }}>
                      <span style={{ width: 16, height: 16, borderRadius: '50%', border: '1.5px solid var(--bb-gold-deep)', background: active ? 'var(--bb-burgundy)' : 'transparent' }}></span>
                      <span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.2em', color: 'var(--bb-gold-deep)' }}>{s.tag}</span>
                        <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-burgundy-deep)' }}>{s.when} · {s.range}</span>
                      </span>
                      <span style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: s.fee ? 'var(--bb-gold-deep)' : 'var(--success)' }}>{s.fee ? `+₹${s.fee}` : 'Free'}</span>
                    </button>
                  );
                })}
              </div>

              {/* cutoff timer */}
              <div style={{ padding: '11px 14px', background: 'var(--bb-burgundy-deep)', borderRadius: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
                  <span className="meta" style={{ color: 'var(--bb-gold-light)' }}>NOW · {now.toLocaleString('en-IN', { weekday: 'short' }).toUpperCase()}</span>
                  <span style={{ fontFamily: 'var(--font-serif)', color: 'var(--bb-ivory)', fontSize: 17, fontVariantNumeric: 'tabular-nums' }}>{pad(now.getHours() % 12 || 12)}:{pad(now.getMinutes())} {now.getHours() >= 12 ? 'PM' : 'AM'}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'rgba(250,246,236,0.88)' }}>
                  {inWindow
                    ? <>Order in <span style={{ color: 'var(--bb-gold-light)', fontVariantNumeric: 'tabular-nums' }}>{pad(hh)}h {pad(mm)}m {pad(ss)}s</span> for standard same-day.</>
                    : <>Standard window closed — express &amp; midnight may still be live.</>}
                </div>
              </div>
            </div>

            {/* summary */}
            <div style={{ ...SD_CARD, background: 'var(--bb-burgundy-deep)', border: '1px solid var(--bb-burgundy-deep)' }}>
              <div className="bb-eyebrow" style={{ color: 'var(--bb-gold-light)', marginBottom: 14 }}>YOUR GIFT</div>
              <SDRow k={`${box.name} × ${qty}`} v={`₹${itemTotal.toLocaleString('en-IN')}`} />
              {SD.ADDONS.filter((a) => addons[a.id]).map((a) => <SDRow key={a.id} k={a.name} v={`+₹${a.price}`} mute />)}
              <SDRow k={`Delivery — ${slot.tag.toLowerCase()}`} v={slot.fee ? `₹${slot.fee}` : 'Free'} mute />
              {serviceable && (city || pincode) && <SDRow k="Deliver to" v={`${city || 'Selected city'}${pincode ? ' · ' + pincode : ''}`} mute />}
              <div style={{ height: 1, background: 'rgba(225,200,146,0.3)', margin: '10px 0' }}></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 12, letterSpacing: '0.2em', color: 'var(--bb-gold-light)' }}>TOTAL</span>
                <span style={{ fontFamily: 'var(--font-serif)', fontSize: 30, color: 'var(--bb-ivory)' }}>₹{total.toLocaleString('en-IN')}</span>
              </div>
              <button className="btn btn-foil" onClick={send} disabled={!canSend || sending} style={{ width: '100%', padding: '16px 24px', opacity: (canSend && !sending) ? 1 : 0.5, cursor: (canSend && !sending) ? 'pointer' : 'not-allowed' }}>
                {done ? 'Gift on its way ✓' : sending ? 'Placing order…' : 'Send the Gift →'}
              </button>
              {sendErr && (
                <div style={{ marginTop: 8, padding: '10px 14px', background: 'rgba(140,46,46,0.2)', border: '1px solid rgba(140,46,46,0.5)', borderRadius: 8, color: '#F5A0A0', fontFamily: 'var(--font-serif)', fontSize: 13 }}>
                  {sendErr}
                </div>
              )}
              <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'rgba(225,200,146,0.7)', textAlign: 'center', marginTop: 10 }}>
                {done
                  ? <>To {rName || 'your recipient'}{city ? ` in ${city}` : ''}{pincode ? ` · ${pincode}` : ''}. Track via WhatsApp.</>
                  : !pinResult
                    ? <>Enter a delivery pincode to confirm availability.</>
                    : !serviceable
                      ? <>We don't deliver to {pincode} yet — enquire about shipping.</>
                      : !canSend
                        ? <>Add the recipient's name &amp; address to send.</>
                        : <>Free returns within 30 min · live WhatsApp tracking.</>}
              </div>
            </div>
          </div>
        </div>

        {/* cities strip */}
        <div className="bb-reveal" style={{ marginTop: 'var(--s-7)', paddingTop: 22, borderTop: '1px solid var(--line-gold)' }}>
          <div className="bb-eyebrow" style={{ marginBottom: 12 }}>SAME-DAY CITIES</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {SD.CITIES.map((c) => (
              <span key={c} style={{ fontFamily: 'var(--font-ui)', fontSize: 12, letterSpacing: '0.04em', padding: '6px 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: 14, color: 'var(--fg-3)', alignSelf: 'center', marginLeft: 6 }}>
              Other PIN codes — next-day, by air.
            </span>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 920px) {
          .bb-sd-grid { grid-template-columns: 1fr !important; }
          .bb-sd-summary { position: static !important; }
        }
        @media (max-width: 520px) {
          .bb-sd-boxes, .bb-sd-addons { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

const SD_CARD = { background: 'var(--bb-pearl)', border: '1px solid var(--line)', borderRadius: 18, padding: 24, boxShadow: 'var(--shadow-1)' };
const SD_QTY = { width: 30, height: 30, borderRadius: '50%', background: 'var(--bb-pearl)', color: 'var(--bb-burgundy)', border: '1px solid var(--line-strong)', cursor: 'pointer', fontSize: 17, fontFamily: 'var(--font-serif)' };
const SD_LBL = { display: 'block', fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.24em', color: 'var(--bb-gold-deep)', marginBottom: 6 };
const SD_INPUT = { width: '100%', padding: '11px 13px', background: 'var(--bb-cream)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--bb-cocoa)', outline: 'none', fontFamily: 'var(--font-serif)', fontSize: 15 };

function SDStep({ n, label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
      <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--bb-burgundy)', color: 'var(--bb-gold-light)', fontFamily: 'var(--font-display)', fontSize: 11, display: 'grid', placeItems: 'center', fontWeight: 600 }}>{n}</span>
      <span className="bb-eyebrow" style={{ fontSize: 11 }}>{label}</span>
    </div>
  );
}

function SDRow({ k, v, mute }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontFamily: 'var(--font-serif)', fontSize: 14, color: mute ? 'rgba(250,246,236,0.72)' : 'var(--bb-ivory)' }}>
      <span style={{ fontStyle: mute ? 'italic' : 'normal' }}>{k}</span><span>{v}</span>
    </div>
  );
}

function SDMap({ geo, onDetect }) {
  const located = geo && geo.state === 'ok';
  const locating = geo && geo.state === 'locating';
  return (
    <div style={{ position: 'relative', borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)' }}>
      {/* stylised map (decorative — real map drops in via your maps provider) */}
      <svg viewBox="0 0 320 130" width="100%" height="130" style={{ display: 'block' }} aria-hidden="true">
        <rect width="320" height="130" fill="#EFE7D4" />
        <g stroke="#DCCBA6" strokeWidth="2" fill="none">
          <path d="M-10 34 H330 M-10 78 H330 M44 -10 V140 M128 -10 V140 M214 -10 V140 M276 -10 V140" />
        </g>
        <g stroke="#CDBB95" strokeWidth="7" fill="none" strokeLinecap="round">
          <path d="M-10 56 H128 L170 98 H330" />
          <path d="M214 -10 V44 L170 98" />
        </g>
        <rect x="52" y="12" width="58" height="30" rx="2" fill="#E5D7B7" />
        <rect x="232" y="84" width="60" height="36" rx="2" fill="#E5D7B7" />
        <circle cx="150" cy="22" r="11" fill="#D9E3C8" />
        <circle cx="40" cy="104" r="9" fill="#D9E3C8" />
      </svg>
      {/* centre pin */}
      <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-100%)' }}>
        {located && <span style={{ position: 'absolute', left: '50%', bottom: -5, transform: 'translateX(-50%)', width: 28, height: 28, borderRadius: '50%', background: 'rgba(91,31,46,0.28)', animation: 'bb-pulse 2.2s ease-out infinite' }}></span>}
        <svg width="32" height="32" viewBox="0 0 24 24" fill="var(--bb-burgundy)" stroke="var(--bb-gold-light)" strokeWidth="1.1" style={{ filter: 'drop-shadow(0 3px 5px rgba(58,36,24,0.4))' }}>
          <path d="M12 2C8 2 5 5 5 9c0 5 7 13 7 13s7-8 7-13c0-4-3-7-7-7z" />
          <circle cx="12" cy="9" r="2.4" fill="var(--bb-gold-light)" stroke="none" />
        </svg>
      </div>
      {/* readout */}
      <div style={{ position: 'absolute', left: 10, top: 10, fontFamily: 'var(--font-ui)', fontSize: 10.5, lineHeight: 1.3, color: 'var(--bb-burgundy-deep)', background: 'rgba(250,252,245,0.88)', borderRadius: 6, padding: '5px 9px', maxWidth: 210 }}>
        {!geo && 'Drop a pin or enter a pincode below'}
        {locating && 'Finding you…'}
        {located && <>Located · {geo.lat}, {geo.lng}<br /><span style={{ color: 'var(--bb-gold-deep)' }}>Confirm your pincode →</span></>}
        {geo && geo.state === 'denied' && 'Location blocked — enter pincode below'}
        {geo && geo.state === 'unsupported' && 'Enter your pincode below'}
      </div>
      {/* detect button */}
      <button onClick={onDetect} style={{
        position: 'absolute', right: 10, bottom: 10, display: 'inline-flex', alignItems: 'center', gap: 7,
        background: 'var(--bb-pearl)', border: '1px solid var(--line-strong)', borderRadius: 8, padding: '8px 12px', cursor: 'pointer',
        fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.16em', color: 'var(--bb-burgundy-deep)'
      }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><circle cx="12" cy="12" r="3" /><path d="M12 2v3M12 19v3M2 12h3M19 12h3" /></svg>
        {locating ? 'LOCATING…' : 'DETECT LOCATION'}
      </button>
    </div>
  );
}

function SDPinBanner({ r }) {
  const styles = {
    'same-day': { bg: 'rgba(79,107,58,0.12)',  bd: 'rgba(79,107,58,0.42)',  fg: '#3F5A2A', title: 'Same-day delivery available', sub: r.city ? `We hand-deliver across ${r.city} today.` : 'We hand-deliver here today.' },
    'next-day': { bg: 'rgba(184,137,58,0.14)',  bd: 'rgba(184,137,58,0.48)', fg: '#8A6520', title: 'Next-day delivery by air',    sub: 'Same-day isn\u2019t available at this pincode — we\u2019ll deliver tomorrow.' },
    'none':     { bg: 'rgba(140,46,46,0.10)',   bd: 'rgba(140,46,46,0.42)',  fg: '#8C2E2E', title: 'Not serviceable yet',          sub: 'We don\u2019t deliver to this pincode. Enquire about shipping instead.' },
    'invalid':  { bg: 'var(--bb-cream)',        bd: 'var(--line)',           fg: 'var(--fg-2)', title: 'Enter a valid 6-digit pincode', sub: 'We\u2019ll check serviceability instantly.' }
  };
  const m = styles[r.status] || styles.invalid;
  return (
    <div style={{ marginTop: 12, padding: '12px 14px', background: m.bg, border: `1px solid ${m.bd}`, borderRadius: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: m.fg, flex: '0 0 auto' }}></span>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em', color: m.fg, textTransform: 'uppercase' }}>{m.title}</span>
      </div>
      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--fg-2)', marginTop: 5 }}>{m.sub}</div>
      {r.status === 'none' && (
        <button onClick={() => window.bbEnquire('Something else')} style={{ marginTop: 8, background: 'transparent', border: 'none', color: 'var(--bb-burgundy)', fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em', cursor: 'pointer', padding: 0 }}>ENQUIRE ABOUT SHIPPING →</button>
      )}
    </div>
  );
}

window.SameDay = SameDay;
