function CartDrawer({ items, isOpen, onClose, onRemove, onUpdateQty, onClearCart }) {
  const total = items.reduce((s, i) => s + i.coffee.prices[i.gram] * i.qty, 0);
  const count  = items.reduce((s, i) => s + i.qty, 0);

  const [checkoutState,  setCheckoutState]  = React.useState(null); // null | 'form' | 'confirmed'
  const [coForm,         setCoForm]         = React.useState({ name: '', email: '' });
  const [coErr,          setCoErr]          = React.useState({});
  const [placing,        setPlacing]        = React.useState(false);
  const [confirmedOrder, setConfirmedOrder] = React.useState(null);

  const session = window.UmbraDB?.getSession?.() || null;

  // Reset checkout state when drawer closes
  React.useEffect(() => {
    if (!isOpen) { setCheckoutState(null); setCoForm({ name:'', email:'' }); setCoErr({}); }
  }, [isOpen]);

  function placeOrder() {
    const errs = {};
    if (!session) {
      if (!coForm.name.trim())          errs.name  = 'Required';
      if (!coForm.email.includes('@'))  errs.email = 'Valid email required';
    }
    if (Object.keys(errs).length) { setCoErr(errs); return; }
    setPlacing(true);
    setTimeout(() => {
      const customer = session
        ? { name: `${session.firstName} ${session.lastName}`, email: session.email }
        : { name: coForm.name, email: coForm.email };
      const address = session?.address || {};
      const order = window.UmbraDB?.saveOrder?.(items, customer, address);
      setConfirmedOrder(order);
      setCheckoutState('confirmed');
      setPlacing(false);
    }, 900);
  }

  return (
    <>
      {/* Backdrop */}
      {isOpen && (
        <div onClick={onClose} style={{
          position: 'fixed', inset: 0, zIndex: 1999,
          background: 'rgba(0,0,0,0.55)',
          animation: 'fadeIn 0.25s ease',
        }} />
      )}

      {/* Drawer */}
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 420, zIndex: 2000,
        background: '#ffffff', color: '#000000',
        display: 'flex', flexDirection: 'column',
        transform: isOpen ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform 0.42s cubic-bezier(0.16, 1, 0.3, 1)',
        borderLeft: '1px solid rgba(0,0,0,0.12)',
      }}>

        {/* Header */}
        <div style={{
          padding: '28px 32px 22px',
          borderBottom: '1px solid rgba(0,0,0,0.1)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        }}>
          <div>
            <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 22, fontWeight: 900, letterSpacing: '0.02em' }}>
              YOUR CART
            </div>
            <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.22em', color: 'rgba(0,0,0,0.4)', marginTop: 4 }}>
              {count} {count === 1 ? 'ITEM' : 'ITEMS'}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'crosshair',
            fontFamily: "'Montserrat', sans-serif", fontSize: 12,
            letterSpacing: '0.2em', color: 'rgba(0,0,0,0.45)',
            transition: 'color 0.15s',
          }}
          onMouseEnter={e => e.currentTarget.style.color = '#000000'}
          onMouseLeave={e => e.currentTarget.style.color = 'rgba(0,0,0,0.45)'}
          >CLOSE ×</button>
        </div>

        {/* Items */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {items.length === 0 ? (
            <div style={{
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              height: '100%', gap: 16,
              fontFamily: "'Montserrat', sans-serif",
              fontSize: 12, letterSpacing: '0.2em',
              color: 'rgba(0,0,0,0.3)',
            }}>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 28, fontStyle: 'italic', color: 'rgba(0,0,0,0.2)' }}>
                Empty
              </div>
              <div>NO ITEMS IN CART</div>
            </div>
          ) : items.map((item, idx) => (
            <div key={`${item.coffee.id}-${item.gram}`} style={{
              padding: '20px 32px',
              borderBottom: '1px solid rgba(0,0,0,0.07)',
              display: 'grid', gridTemplateColumns: '1fr auto',
              alignItems: 'start', gap: 16,
            }}>
              <div>
                <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 18, fontWeight: 700 }}>
                  {item.coffee.name}
                </div>
                <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.15em', color: 'rgba(0,0,0,0.45)', marginTop: 4 }}>
                  {item.coffee.origin}
                </div>
                <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.1em', color: 'rgba(0,0,0,0.55)', marginTop: 8 }}>
                  {item.gram} · ${item.coffee.prices[item.gram]}
                </div>
                {/* Qty controls */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12 }}>
                  <button onClick={() => onUpdateQty(idx, item.qty - 1)} style={{ background: 'none', border: '1px solid rgba(0,0,0,0.25)', width: 26, height: 26, cursor: 'crosshair', fontFamily: "'Montserrat', sans-serif", fontSize: 14, color: '#000000', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>−</button>
                  <span style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, minWidth: 16, textAlign: 'center' }}>{item.qty}</span>
                  <button onClick={() => onUpdateQty(idx, item.qty + 1)} style={{ background: 'none', border: '1px solid rgba(0,0,0,0.25)', width: 26, height: 26, cursor: 'crosshair', fontFamily: "'Montserrat', sans-serif", fontSize: 14, color: '#000000', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+</button>
                  <button onClick={() => onRemove(idx)} style={{ background: 'none', border: 'none', cursor: 'crosshair', fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.15em', color: 'rgba(0,0,0,0.35)', marginLeft: 8, transition: 'color 0.15s' }}
                  onMouseEnter={e => e.currentTarget.style.color = '#000000'}
                  onMouseLeave={e => e.currentTarget.style.color = 'rgba(0,0,0,0.35)'}
                  >REMOVE</button>
                </div>
              </div>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 20, fontWeight: 700, textAlign: 'right', paddingTop: 2 }}>
                ${item.coffee.prices[item.gram] * item.qty}
              </div>
            </div>
          ))}
        </div>

        {/* Checkout footer */}
        {items.length > 0 && !checkoutState && (
          <div style={{ borderTop: '1px solid rgba(0,0,0,0.12)', padding: '24px 32px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 20 }}>
              <span style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.25em' }}>SUBTOTAL</span>
              <span style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 28, fontWeight: 900 }}>${total}</span>
            </div>
            <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.15em', color: 'rgba(0,0,0,0.4)', marginBottom: 16, lineHeight: 1.7 }}>
              Shipping calculated at checkout.<br />Free shipping on orders over $120.
            </div>
            <button onClick={() => setCheckoutState('form')} style={{
              width: '100%', padding: '18px',
              background: '#000000', color: '#ffffff',
              border: 'none', fontFamily: "'Montserrat', sans-serif",
              fontSize: 12, letterSpacing: '0.22em',
              cursor: 'crosshair', transition: 'opacity 0.15s',
            }}
            onMouseEnter={e => e.currentTarget.style.opacity='0.85'}
            onMouseLeave={e => e.currentTarget.style.opacity='1'}
            >PROCEED TO CHECKOUT</button>
          </div>
        )}

        {/* Checkout form */}
        {checkoutState === 'form' && (
          <div style={{ borderTop: '1px solid rgba(0,0,0,0.12)', padding: '24px 32px' }}>
            <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 18, fontWeight: 900, marginBottom: 20 }}>Checkout</div>
            {!session && (
              <>
                {[['Name', 'name', 'text'], ['Email', 'email', 'email']].map(([l, k, t]) => (
                  <div key={k} style={{ marginBottom: 16 }}>
                    <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.22em', color: 'rgba(0,0,0,0.45)', marginBottom: 5 }}>{l.toUpperCase()}{coErr[k] && <span style={{ marginLeft: 8 }}>— {coErr[k]}</span>}</div>
                    <input type={t} value={coForm[k]} onChange={e => { setCoForm(f=>({...f,[k]:e.target.value})); setCoErr(r=>({...r,[k]:''})); }}
                      style={{ width:'100%', border:'none', borderBottom:`1px solid ${coErr[k]?'rgba(0,0,0,0.6)':'rgba(0,0,0,0.2)'}`, padding:'8px 0', fontFamily:"'Montserrat',monospace", fontSize:11, background:'none', outline:'none' }} />
                  </div>
                ))}
              </>
            )}
            {session && (
              <div style={{ fontFamily:"'Montserrat',monospace", fontSize:10, color:'rgba(0,0,0,0.55)', marginBottom:20, padding:'10px 14px', background:'rgba(0,0,0,0.05)' }}>
                Ordering as <strong>{session.firstName} {session.lastName}</strong><br/><span style={{opacity:0.7}}>{session.email}</span>
              </div>
            )}
            <div style={{ fontFamily:"'Montserrat',monospace", fontSize:9, color:'rgba(0,0,0,0.4)', letterSpacing:'0.12em', marginBottom:20 }}>
              Total: <strong style={{ fontFamily:"'Montserrat',serif", fontSize:20 }}>${total}</strong>
            </div>
            <button onClick={placeOrder} style={{
              width:'100%', padding:'16px',
              background: placing ? 'rgba(0,0,0,0.5)' : '#000000', color:'#ffffff',
              border:'none', fontFamily:"'Montserrat',monospace",
              fontSize:11, letterSpacing:'0.22em',
              cursor: placing ? 'wait' : 'crosshair',
            }}>{placing ? '···' : 'PLACE ORDER'}</button>
            <button onClick={() => setCheckoutState(null)} style={{ width:'100%', marginTop:10, padding:'12px', background:'transparent', border:'1px solid rgba(0,0,0,0.15)', fontFamily:"'Montserrat',monospace", fontSize:9, letterSpacing:'0.2em', color:'rgba(0,0,0,0.45)', cursor:'crosshair' }}>← BACK TO CART</button>
          </div>
        )}

        {/* Order confirmation */}
        {checkoutState === 'confirmed' && confirmedOrder && (
          <div style={{ borderTop:'1px solid rgba(0,0,0,0.12)', padding:'32px' }}>
            <div style={{ fontFamily:"'Montserrat',serif", fontSize:26, fontWeight:900, marginBottom:8 }}>Order placed.</div>
            <div style={{ fontFamily:"'Montserrat',monospace", fontSize:9, letterSpacing:'0.18em', color:'rgba(0,0,0,0.45)', marginBottom:20 }}>#{confirmedOrder.id}</div>
            <div style={{ fontFamily:"'Montserrat',monospace", fontSize:10, lineHeight:1.9, color:'rgba(0,0,0,0.55)', marginBottom:24 }}>
              A confirmation will be sent to<br/><strong>{confirmedOrder.customer.email}</strong>.<br/>We roast to order — expect dispatch within 48 hours.
            </div>
            <button onClick={() => { onClearCart(); setCheckoutState(null); onClose(); }} style={{ width:'100%', padding:'16px', background:'#000000', color:'#ffffff', border:'none', fontFamily:"'Montserrat',monospace", fontSize:11, letterSpacing:'0.22em', cursor:'crosshair' }}>DONE</button>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { CartDrawer });
