// CartDrawer.jsx — slide-in cart + checkout flow

function CartDrawer() {
  const [open, setOpen]     = React.useState(false);
  const [cart, setCart]     = React.useState(window.BB_STORE.cart.slice());
  const [step, setStep]     = React.useState('cart');    // 'cart' | 'checkout' | 'done'
  const [addons, setAddons] = React.useState({});
  // checkout fields
  const [occasion, setOccasion] = React.useState('');
  const [note, setNote]         = React.useState('');
  const [rName, setRName]       = React.useState('');
  const [rPhone, setRPhone]     = React.useState('');
  const [email, setEmail]       = React.useState(window.BB_STORE.user?.email || '');
  const [pincode, setPincode]   = React.useState('');
  const [pinResult, setPinResult] = React.useState(null);
  const [addr, setAddr]         = React.useState({ flat: '', street: '', area: '' });
  const [city, setCity]         = React.useState('');
  const [slotId, setSlotId]     = React.useState('today-eve');
  const [payMethod, setPayMethod] = React.useState('upi');
  const [sending, setSending]   = React.useState(false);
  const [sendErr, setSendErr]   = React.useState('');

  React.useEffect(() => {
    const onOpen   = () => { setOpen(true); setStep('cart'); };
    const onUpdate = () => setCart(window.BB_STORE.cart.slice());
    window.addEventListener('bb-open-cart',   onOpen);
    window.addEventListener('bb-cart-update', onUpdate);
    return () => {
      window.removeEventListener('bb-open-cart',   onOpen);
      window.removeEventListener('bb-cart-update', onUpdate);
    };
  }, []);

  const close = () => setOpen(false);

  // Pincode logic (uses shared gsCheckPin from GiftShop.jsx)
  const checkPin = (val) => {
    const r = window.gsCheckPin(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 serviceable = pinResult && (pinResult.status === 'same-day' || pinResult.status === 'next-day');
  const canOrder    = serviceable && rName.trim() && addr.flat.trim();

  // Totals
  const subtotal    = window.BB_STORE.cartTotal();
  const addonList   = (window.GS_ADDONS || []);
  const addonTotal  = addonList.filter(a => addons[a.id]).reduce((s, a) => s + a.price, 0);
  const slots       = window.GS_DELIVERY_SLOTS || [];
  const slot        = slots.find(s => s.id === slotId) || slots[0] || {};
  const grandTotal  = subtotal + addonTotal + (slot.fee || 0);

  const placeOrder = async () => {
    setSending(true); setSendErr('');
    try {
      const user = window.BB_STORE.user;
      const res = await fetch('/api/order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(user ? { 'x-user-token': user.token } : {}) },
        body: JSON.stringify({
          items: cart, addons, note, occasion,
          recipient: { name: rName, phone: rPhone },
          customerEmail: email,
          pincode, address: addr, city,
          slot: slot ? { when: slot.when, range: slot.range, tag: slot.tag } : {},
          paymentMethod: payMethod,
          total: grandTotal,
        }),
      });
      if (!res.ok) throw new Error('Server error');
      window.BB_STORE.clearCart();
      window.BB_STORE.notify('Your gift is on its way! 🎁', 'success');
      setStep('done');
    } catch {
      setSendErr('Could not place order — please WhatsApp us directly.');
    } finally {
      setSending(false);
    }
  };

  const OCCASIONS = ['Thank you', 'Congratulations', 'Happy Birthday', 'Welcome', 'Sorry', 'Just because'];

  const INPUT = { width: '100%', padding: '10px 12px', background: 'var(--bb-cream)', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-cocoa)', outline: 'none', boxSizing: 'border-box' };
  const LBL   = { display: 'block', fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.22em', color: 'var(--bb-gold-deep)', marginBottom: 5, marginTop: 12 };

  if (!open) return null;

  return (
    <>
      {/* Backdrop */}
      <div onClick={close} style={{ position: 'fixed', inset: 0, background: 'rgba(30,10,15,0.55)', zIndex: 7000, backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)' }} />

      {/* Drawer */}
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 440, maxWidth: '100vw', zIndex: 7001, display: 'flex', flexDirection: 'column', background: 'var(--bb-pearl)', boxShadow: '-8px 0 48px rgba(0,0,0,0.32)', border: '1px solid var(--line-gold)', borderRight: 'none' }}>

        {/* Header bar */}
        <div style={{ background: 'var(--bb-burgundy)', padding: '18px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.28em', color: 'var(--bb-gold-light)' }}>
              {step === 'cart' ? 'YOUR CART' : step === 'checkout' ? 'CHECKOUT' : 'ORDER PLACED ✓'}
            </div>
            {step === 'cart' && cart.length > 0 && (
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 12, color: 'rgba(250,246,236,0.65)', marginTop: 2 }}>
                {window.BB_STORE.cartCount()} item{window.BB_STORE.cartCount() !== 1 ? 's' : ''} &nbsp;·&nbsp; &#8377;{subtotal.toLocaleString('en-IN')}
              </div>
            )}
          </div>
          <button onClick={close} style={{ background: 'none', border: 'none', color: 'var(--bb-gold-light)', fontSize: 26, cursor: 'pointer', lineHeight: 1, padding: '2px 6px' }}>&#215;</button>
        </div>

        {/* Progress steps */}
        {step !== 'done' && (
          <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', background: 'var(--bb-cream)', flexShrink: 0 }}>
            {['cart', 'checkout'].map((s, i) => {
              const active = step === s;
              const done   = (s === 'cart' && step === 'checkout');
              return (
                <div key={s} onClick={() => { if (done) setStep(s); }} style={{ flex: 1, padding: '10px 0', textAlign: 'center', cursor: done ? 'pointer' : 'default', borderBottom: active ? '2px solid var(--bb-burgundy)' : '2px solid transparent', transition: 'all 200ms' }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.2em', color: active ? 'var(--bb-burgundy)' : done ? 'var(--bb-gold-deep)' : 'var(--fg-3)' }}>
                    {done ? '✓ ' : (i + 1) + '. '}{s === 'cart' ? 'CART' : 'CHECKOUT'}
                  </span>
                </div>
              );
            })}
          </div>
        )}

        {/* Scrollable content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>

          {/* ── DONE ── */}
          {step === 'done' && (
            <div style={{ textAlign: 'center', paddingTop: 50 }}>
              <div style={{ fontSize: 52, marginBottom: 18 }}>&#127873;</div>
              <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 26, color: 'var(--bb-burgundy-deep)', marginBottom: 14 }}>Gift on its way!</h3>
              <p style={{ fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.65, maxWidth: 320, margin: '0 auto 28px' }}>
                We've received your order and will WhatsApp you with live updates. Thank you for choosing Blissful Bites.
              </p>
              <button className="btn btn-primary" onClick={() => { setStep('cart'); close(); }} style={{ padding: '14px 28px' }}>Continue Shopping</button>
            </div>
          )}

          {/* ── CART ── */}
          {step === 'cart' && (
            <>
              {cart.length === 0 ? (
                <div style={{ textAlign: 'center', paddingTop: 64, color: 'var(--fg-3)' }}>
                  <div style={{ fontSize: 44, marginBottom: 12 }}>&#128717;</div>
                  <p style={{ fontFamily: 'var(--font-serif)', fontSize: 16, marginBottom: 20 }}>Your cart is empty</p>
                  <button className="btn btn-ghost" onClick={close} style={{ padding: '12px 24px' }}>Browse Gifts</button>
                </div>
              ) : (
                <>
                  {/* Cart items */}
                  {cart.map(item => (
                    <div key={item.id} style={{ display: 'flex', gap: 14, padding: '14px 0', borderBottom: '1px solid var(--line)', alignItems: 'flex-start' }}>
                      <img src={item.img} alt={item.name} style={{ width: 68, height: 68, objectFit: 'cover', borderRadius: 10, flex: '0 0 auto', border: '1px solid var(--line)' }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: 'var(--font-display)', fontSize: 8, letterSpacing: '0.2em', color: 'var(--bb-gold-deep)' }}>{item.tag}</div>
                        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, color: 'var(--bb-burgundy-deep)', lineHeight: 1.2, marginBottom: 2 }}>{item.name}</div>
                        <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-3)', marginBottom: 10 }}>{item.count}</div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'var(--bb-cream)', borderRadius: 999, padding: '5px 12px', border: '1px solid var(--line)' }}>
                            <button onClick={() => { if ((item.qty || 1) <= 1) window.BB_STORE.removeFromCart(item.id); else window.BB_STORE.updateQty(item.id, (item.qty || 1) - 1); }} style={{ background: 'none', border: 'none', color: 'var(--bb-burgundy)', fontSize: 18, cursor: 'pointer', lineHeight: 1, padding: '0 2px' }}>&#x2212;</button>
                            <span style={{ fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-burgundy-deep)', minWidth: 16, textAlign: 'center' }}>{item.qty || 1}</span>
                            <button onClick={() => window.BB_STORE.updateQty(item.id, (item.qty || 1) + 1)} style={{ background: 'none', border: 'none', color: 'var(--bb-burgundy)', fontSize: 18, cursor: 'pointer', lineHeight: 1, padding: '0 2px' }}>+</button>
                          </div>
                          <button onClick={() => window.BB_STORE.removeFromCart(item.id)} style={{ background: 'none', border: 'none', color: 'var(--fg-3)', fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.18em', cursor: 'pointer', padding: 0, textDecoration: 'underline' }}>REMOVE</button>
                        </div>
                      </div>
                      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 17, color: 'var(--bb-burgundy-deep)', flex: '0 0 auto', fontWeight: 500 }}>&#8377;{(item.price * (item.qty || 1)).toLocaleString('en-IN')}</div>
                    </div>
                  ))}

                  {/* Add-ons */}
                  <div style={{ marginTop: 22 }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.24em', color: 'var(--bb-gold-deep)', marginBottom: 12 }}>ADD A LITTLE EXTRA</div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                      {addonList.map(a => {
                        const on = !!addons[a.id];
                        return (
                          <label key={a.id} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', padding: '10px 12px', 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' }}>
                            <input type="checkbox" checked={on} onChange={() => setAddons(x => ({ ...x, [a.id]: !x[a.id] }))} style={{ display: 'none' }} />
                            <span style={{ width: 17, height: 17, borderRadius: 4, border: '1.5px solid var(--bb-gold-deep)', background: on ? 'var(--bb-burgundy)' : 'transparent', display: 'grid', placeItems: 'center', flex: '0 0 auto', marginTop: 1 }}>
                              {on && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="var(--bb-gold-light)" strokeWidth="3"><path d="M5 12l5 5L20 7"/></svg>}
                            </span>
                            <span style={{ flex: 1 }}>
                              <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 13, color: 'var(--bb-burgundy-deep)', lineHeight: 1.2 }}>{a.name}</span>
                              <span style={{ display: 'block', fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 11, color: 'var(--fg-3)' }}>+&#8377;{a.price}</span>
                            </span>
                          </label>
                        );
                      })}
                    </div>
                  </div>
                </>
              )}
            </>
          )}

          {/* ── CHECKOUT ── */}
          {step === 'checkout' && (
            <div>
              <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 14, color: 'var(--fg-3)', marginBottom: 16, marginTop: 0 }}>Fill in delivery details to send your gift.</p>

              {/* Occasion */}
              <div style={{ marginBottom: 16 }}>
                <span style={LBL}>OCCASION</span>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {OCCASIONS.map(o => (
                    <button key={o} onClick={() => setOccasion(o)} style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.14em', padding: '6px 12px', borderRadius: 999, cursor: 'pointer', border: occasion === o ? '1px solid var(--bb-burgundy)' : '1px solid var(--line-strong)', background: occasion === o ? 'var(--bb-burgundy)' : 'transparent', color: occasion === o ? 'var(--bb-ivory)' : 'var(--bb-cocoa)', transition: 'all 200ms' }}>{o}</button>
                  ))}
                </div>
              </div>

              {/* Note */}
              <span style={LBL}>GIFT NOTE (optional)</span>
              <textarea value={note} onChange={e => setNote(e.target.value)} maxLength={200} placeholder="A personal message for the recipient…" style={{ ...INPUT, resize: 'vertical', minHeight: 72, lineHeight: 1.5 }} />

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

              <span style={LBL}>EMAIL (optional — for order updates)</span>
              <input value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" type="email" style={INPUT} />

              {/* Pincode */}
              <span style={LBL}>DELIVERY PINCODE *</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <input value={pincode} onChange={onPin} inputMode="numeric" placeholder="6-digit pincode" style={{ ...INPUT, flex: 1, letterSpacing: '0.1em' }} />
                <button onClick={() => checkPin(pincode)} disabled={pincode.length !== 6} style={{ fontFamily: 'var(--font-display)', fontSize: 9, letterSpacing: '0.16em', padding: '0 14px', 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 && <GS_PinBanner r={pinResult} />}

              {serviceable && (
                <>
                  <span style={LBL}>FLAT / HOUSE NO. *</span>
                  <input value={addr.flat} onChange={e => setAddr(a => ({ ...a, flat: e.target.value }))} placeholder="Flat 14B, Acacia Tower" style={INPUT} />
                  <span style={LBL}>BUILDING & STREET</span>
                  <input value={addr.street} onChange={e => setAddr(a => ({ ...a, street: e.target.value }))} placeholder="Hill Road, Bandra West" style={INPUT} />
                  <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 8 }}>
                    <div>
                      <span style={LBL}>AREA / LANDMARK</span>
                      <input value={addr.area} onChange={e => setAddr(a => ({ ...a, area: e.target.value }))} placeholder="Near Mehboob Studio" style={INPUT} />
                    </div>
                    <div>
                      <span style={LBL}>CITY</span>
                      <input value={city} onChange={e => setCity(e.target.value)} placeholder="City" style={INPUT} />
                    </div>
                  </div>

                  {/* Delivery slot */}
                  <span style={LBL}>DELIVERY WINDOW</span>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                    {slots.map(s => {
                      const active = s.id === slotId;
                      return (
                        <button key={s.id} onClick={() => setSlotId(s.id)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 13px', borderRadius: 9, cursor: 'pointer', background: active ? 'var(--bb-cream)' : 'var(--bb-pearl)', border: active ? '1.5px solid var(--bb-gold)' : '1px solid var(--line)', transition: 'all 200ms' }}>
                          <span style={{ fontFamily: 'var(--font-serif)', fontSize: 14, color: 'var(--bb-burgundy-deep)' }}>{s.when} &middot; {s.range}</span>
                          <span style={{ fontFamily: 'var(--font-display)', fontSize: 8.5, letterSpacing: '0.14em', color: s.fee ? 'var(--bb-gold-deep)' : 'var(--success)' }}>{s.fee ? '+₹' + s.fee : 'FREE'}</span>
                        </button>
                      );
                    })}
                  </div>

                  {/* Payment method */}
                  <span style={LBL}>PAYMENT METHOD</span>
                  <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                    {[{ 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-burgundy)' : '1px solid var(--line-strong)',
                        background: payMethod === p.k ? 'var(--bb-burgundy)' : 'transparent',
                        color: payMethod === p.k ? 'var(--bb-ivory)' : 'var(--bb-cocoa)', transition: 'all 200ms'
                      }}>{p.label}</button>
                    ))}
                  </div>
                  {payMethod === 'upi' && <UpiQr amount={grandTotal} note={`Blissful Bites order — ${rName || 'gift'}`} />}
                  {payMethod === 'cod' && (
                    <div style={{ padding: '12px 14px', background: 'var(--bb-cream)', border: '1px solid var(--line)', borderRadius: 10, fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-2)' }}>
                      Pay in cash when your gift arrives at the door.
                    </div>
                  )}
                </>
              )}

              {sendErr && <div style={{ marginTop: 14, padding: '11px 14px', background: 'rgba(140,46,46,0.08)', border: '1px solid rgba(140,46,46,0.3)', borderRadius: 8, color: '#8C2E2E', fontFamily: 'var(--font-serif)', fontSize: 13 }}>{sendErr}</div>}
            </div>
          )}
        </div>

        {/* ── Footer CTA ── */}
        {step !== 'done' && cart.length > 0 && (
          <div style={{ padding: '16px 24px', borderTop: '1px solid var(--line)', background: 'var(--bb-pearl)', flexShrink: 0 }}>
            {/* Summary line */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <div>
                {step === 'cart' && addonTotal > 0 && <div style={{ fontFamily: 'var(--font-serif)', fontSize: 13, color: 'var(--fg-3)', marginBottom: 2 }}>Add-ons +&#8377;{addonTotal.toLocaleString('en-IN')}</div>}
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.16em', color: 'var(--fg-2)' }}>TOTAL</div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 24, color: 'var(--bb-burgundy-deep)', fontWeight: 600, lineHeight: 1.1 }}>&#8377;{(step === 'cart' ? subtotal + addonTotal : grandTotal).toLocaleString('en-IN')}</div>
              </div>
              {step === 'checkout' && !canOrder && (
                <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-3)', maxWidth: 160, textAlign: 'right' }}>
                  {!rName.trim() ? 'Enter recipient name.' : !pincode ? 'Enter pincode.' : !serviceable ? 'Pincode not serviceable.' : 'Enter flat/house number.'}
                </div>
              )}
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              {step === 'checkout' && (
                <button onClick={() => setStep('cart')} className="btn btn-ghost" style={{ flex: '0 0 auto', padding: '12px 16px' }}>&#8592; Back</button>
              )}
              {step === 'cart' && (
                <button className="btn btn-primary" onClick={() => setStep('checkout')} style={{ flex: 1, padding: '14px 0' }}>
                  Proceed to Checkout &#8594;
                </button>
              )}
              {step === 'checkout' && (
                <button className="btn btn-foil" onClick={placeOrder} disabled={!canOrder || sending} style={{ flex: 1, padding: '14px 0', opacity: (canOrder && !sending) ? 1 : 0.5, cursor: (canOrder && !sending) ? 'pointer' : 'not-allowed' }}>
                  {sending ? 'Placing Order…' : payMethod === 'upi' ? "I've Paid — Place Order →" : 'Place Order (Cash on Delivery) →'}
                </button>
              )}
            </div>
            {!window.BB_STORE.user && (
              <p style={{ marginTop: 10, fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-3)', textAlign: 'center' }}>
                <button onClick={() => window.BB_STORE.openAuth('login')} style={{ background: 'none', border: 'none', color: 'var(--bb-burgundy)', cursor: 'pointer', fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 12, padding: 0 }}>Sign in</button>
                {' '}to save your order history.
              </p>
            )}
          </div>
        )}
      </div>
    </>
  );
}

window.CartDrawer = CartDrawer;
