// DGCart.jsx — cart sidebar (slide-in) + checkout modal

const { useState: useCartSt } = React;

/* ── Cart Sidebar ─────────────────────────────────────────── */
const DGCart = ({ open, cart, onClose, onUpdate, onCheckout }) => {
  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const count = cart.reduce((s, i) => s + i.qty, 0);

  return (
    <>
      <div style={{ ...cartSt.overlay, opacity: open ? 1 : 0, pointerEvents: open ? 'all' : 'none' }}
           onClick={onClose} />
      <div style={{ ...cartSt.sidebar, transform: open ? 'translateX(0)' : 'translateX(100%)' }}>
        <div style={cartSt.header}>
          <h3 style={cartSt.headerTitle}>Your Order</h3>
          <button style={cartSt.closeBtn} onClick={onClose}
            onMouseEnter={e => e.currentTarget.style.color = '#B8904A'}
            onMouseLeave={e => e.currentTarget.style.color = 'rgba(242,236,220,0.4)'}>✕</button>
        </div>

        <div style={cartSt.items}>
          {cart.length === 0 ? (
            <p style={cartSt.empty}>Your cart is empty.</p>
          ) : (
            cart.map(item => (
              <div key={item.id} style={cartSt.item}>
                <div style={cartSt.itemBottle}>
                  <svg viewBox="0 0 36 72" width="28" height="56" fill="none">
                    <ellipse cx="18" cy="5" rx="5" ry="4" fill="#111"/>
                    <rect x="16" y="8" width="4" height="7" fill="#111"/>
                    <rect x="13" y="14" width="10" height="6" rx="1" fill="#1A1A1A"/>
                    <rect x="15" y="19" width="6" height="7" fill={item.bottleColor || '#5C2E0A'}/>
                    <path d="M8 32 Q8 26 15 26 L21 26 Q28 26 28 32" fill={item.bottleColor || '#5C2E0A'}/>
                    <rect x="8" y="32" width="20" height="36" rx="1" fill={item.bottleColor || '#5C2E0A'}/>
                    <rect x="10" y="37" width="16" height="20" fill="rgba(242,236,220,0.1)"/>
                    <line x1="11" y1="41" x2="25" y2="41" stroke="#B8904A" strokeWidth="0.5" opacity="0.7"/>
                  </svg>
                </div>
                <div style={cartSt.itemInfo}>
                  <p style={cartSt.itemName}>{item.name}</p>
                  <p style={cartSt.itemPrice}>${item.price.toFixed(2)} each</p>
                </div>
                <div style={cartSt.qtyControls}>
                  <button style={cartSt.qtyBtn} onClick={() => onUpdate(item.id, -1)}
                    onMouseEnter={e => { e.currentTarget.style.background = '#B8904A'; e.currentTarget.style.color = '#1A1A1A'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'rgba(242,236,220,0.08)'; e.currentTarget.style.color = '#F2ECDC'; }}>−</button>
                  <span style={cartSt.qtyVal}>{item.qty}</span>
                  <button style={cartSt.qtyBtn} onClick={() => onUpdate(item.id, 1)}
                    onMouseEnter={e => { e.currentTarget.style.background = '#B8904A'; e.currentTarget.style.color = '#1A1A1A'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'rgba(242,236,220,0.08)'; e.currentTarget.style.color = '#F2ECDC'; }}>+</button>
                </div>
              </div>
            ))
          )}
        </div>

        <div style={cartSt.footer}>
          <div style={cartSt.subtotalRow}>
            <span style={cartSt.subtotalLabel}>Subtotal</span>
            <strong style={cartSt.subtotalAmt}>${total.toFixed(2)}</strong>
          </div>
          <p style={cartSt.note}>Pricing is approximate. We'll confirm your total and payment details by email after you place your order.</p>
          <button style={{ ...cartSt.checkoutBtn, opacity: count === 0 ? 0.4 : 1 }}
            disabled={count === 0} onClick={onCheckout}
            onMouseEnter={e => { if (count > 0) e.currentTarget.style.background = '#D4B070'; }}
            onMouseLeave={e => e.currentTarget.style.background = '#B8904A'}>
            Proceed to Checkout
          </button>
        </div>
      </div>
    </>
  );
};

/* ── Checkout Modal ───────────────────────────────────────── */
const DGCheckout = ({ open, cart, onClose, onSuccess }) => {
  const [mode, setMode] = useCartSt('pickup');
  const [f, setF] = useCartSt({ name: '', email: '', phone: '', address: '', city: '', state: '', zip: '', notes: '' });
  const [done, setDone] = useCartSt(false);
  const set = k => e => setF(p => ({ ...p, [k]: e.target.value }));

  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);

  const submit = () => {
    if (!f.name || !f.email) return;
    const fulfillment = mode === 'pickup' ? 'Local Pickup' : 'Ship to Me';
    const itemLines = cart.map(i => `  ${i.name} x${i.qty} — $${(i.price * i.qty).toFixed(2)}`).join('\n');
    const lines = [
      `Fulfillment: ${fulfillment}`,
      `Name: ${f.name}`,
      `Email: ${f.email}`,
      `Phone: ${f.phone || 'Not provided'}`,
      ``,
      `Items:`,
      itemLines,
      `Total: $${total.toFixed(2)}`,
      ...(mode === 'ship' ? [
        ``,
        `Ship to: ${f.address}, ${f.city}, ${f.state} ${f.zip}`,
      ] : []),
      ``,
      `Notes: ${f.notes || 'None'}`,
    ].join('\n');
    window.open(`mailto:dashinggentbitters@gmail.com?subject=${encodeURIComponent(`New Order — ${fulfillment}`)}&body=${encodeURIComponent(lines)}`);
    setDone(true);
    setTimeout(() => { onSuccess(); setDone(false); setF({ name:'',email:'',phone:'',address:'',city:'',state:'',zip:'',notes:'' }); }, 3500);
  };

  const inp = (k, ph, type='text') => (
    <input type={type} style={chkSt.input} value={f[k]} onChange={set(k)} placeholder={ph} />
  );

  return (
    <div style={{ ...chkSt.overlay, opacity: open ? 1 : 0, pointerEvents: open ? 'all' : 'none' }}>
      <div style={{ ...chkSt.modal, transform: open ? 'translateY(0)' : 'translateY(20px)', transition: 'transform 0.3s' }}>
        <button style={chkSt.closeBtn} onClick={onClose}
          onMouseEnter={e => e.currentTarget.style.color = '#B8904A'}
          onMouseLeave={e => e.currentTarget.style.color = 'rgba(242,236,220,0.35)'}>✕</button>

        {done ? (
          <div style={chkSt.successWrap}>
            <p style={chkSt.successStar}>✦</p>
            <h4 style={chkSt.successTitle}>Order Received</h4>
            <p style={chkSt.successBody}>Thanks — we'll follow up at your email address to confirm the details and arrange payment. Expect to hear from us within one business day.</p>
          </div>
        ) : (
          <>
            <h3 style={chkSt.title}>Place Your Order</h3>
            <p style={chkSt.sub}>We'll confirm your order and payment details by email within one business day.</p>

            <div style={chkSt.toggle}>
              {['pickup', 'ship'].map(opt => (
                <button key={opt} style={{ ...chkSt.toggleBtn, ...(mode === opt ? chkSt.toggleActive : {}) }}
                  onClick={() => setMode(opt)}>
                  {opt === 'pickup' ? 'Local Pickup' : 'Ship to Me'}
                </button>
              ))}
            </div>

            <div style={chkSt.summary}>
              <p style={chkSt.summaryLabel}>Order Summary</p>
              {cart.map(item => (
                <div key={item.id} style={chkSt.summaryItem}>
                  <span>{item.name} × {item.qty}</span>
                  <span>${(item.price * item.qty).toFixed(2)}</span>
                </div>
              ))}
              <div style={chkSt.summaryTotal}>
                <span>Total</span><span>${total.toFixed(2)}</span>
              </div>
            </div>

            <div style={chkSt.fg}><label style={chkSt.lbl}>Full Name</label>{inp('name','Jane Smith')}</div>
            <div style={chkSt.fg}><label style={chkSt.lbl}>Email Address</label>{inp('email','jane@example.com','email')}</div>
            <div style={chkSt.fg}><label style={chkSt.lbl}>Phone (optional)</label>{inp('phone','(865) 555-0100','tel')}</div>

            {mode === 'ship' && (
              <>
                <div style={chkSt.fg}><label style={chkSt.lbl}>Street Address</label>{inp('address','123 Main St')}</div>
                <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gap:10 }}>
                  <div style={chkSt.fg}><label style={chkSt.lbl}>City</label>{inp('city','Knoxville')}</div>
                  <div style={chkSt.fg}><label style={chkSt.lbl}>State</label>{inp('state','TN')}</div>
                  <div style={chkSt.fg}><label style={chkSt.lbl}>ZIP</label>{inp('zip','37901')}</div>
                </div>
              </>
            )}

            <div style={chkSt.fg}>
              <label style={chkSt.lbl}>Notes (optional)</label>
              <textarea style={{ ...chkSt.input, minHeight: 68, resize: 'vertical' }}
                value={f.notes} onChange={set('notes')} placeholder="Any special requests…" />
            </div>

            <button style={chkSt.submitBtn} onClick={submit}
              onMouseEnter={e => e.currentTarget.style.background = '#D4B070'}
              onMouseLeave={e => e.currentTarget.style.background = '#B8904A'}>
              Submit Order
            </button>
          </>
        )}
      </div>
    </div>
  );
};

const cartSt = {
  overlay: {
    position: 'fixed', inset: 0, background: 'rgba(26,26,26,0.6)', zIndex: 200,
    transition: 'opacity 0.3s',
  },
  sidebar: {
    position: 'fixed', top: 0, right: 0, width: 400, maxWidth: '100vw', height: '100vh',
    background: '#1A1A1A', borderLeft: '1px solid rgba(184,144,74,0.22)',
    zIndex: 201, display: 'flex', flexDirection: 'column',
    transition: 'transform 0.35s cubic-bezier(.4,0,.2,1)',
  },
  header: {
    padding: '20px 24px', borderBottom: '1px solid rgba(184,144,74,0.18)',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0,
  },
  headerTitle: {
    fontFamily: 'Georgia, serif', fontSize: '1.15rem', fontWeight: 700, color: '#F2ECDC', margin: 0,
  },
  closeBtn: {
    background: 'none', border: 'none', color: 'rgba(242,236,220,0.4)',
    fontSize: '1.3rem', cursor: 'pointer', lineHeight: 1, transition: 'color 0.18s', padding: 4,
  },
  items: { flex: 1, overflowY: 'auto', padding: '16px 24px' },
  empty: {
    textAlign: 'center', padding: '48px 16px',
    fontFamily: 'Georgia, serif', fontStyle: 'italic',
    fontSize: '0.95rem', color: 'rgba(242,236,220,0.28)',
  },
  item: {
    display: 'grid', gridTemplateColumns: '36px 1fr auto',
    gap: 12, alignItems: 'center',
    padding: '14px 0', borderBottom: '1px solid rgba(184,144,74,0.12)',
  },
  itemBottle: { display: 'flex', alignItems: 'center', justifyContent: 'center' },
  itemInfo: {},
  itemName: {
    fontFamily: 'Georgia, serif', fontSize: '0.95rem', fontWeight: 700,
    color: '#F2ECDC', margin: '0 0 3px',
  },
  itemPrice: {
    fontFamily: 'Georgia, serif', fontSize: '0.78rem',
    color: 'rgba(212,176,112,0.7)', margin: 0,
  },
  qtyControls: { display: 'flex', alignItems: 'center', gap: 6 },
  qtyBtn: {
    background: 'rgba(242,236,220,0.08)', border: '1px solid rgba(184,144,74,0.25)',
    color: '#F2ECDC', width: 26, height: 26,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', fontSize: '0.9rem', transition: 'all 0.15s',
  },
  qtyVal: {
    fontFamily: 'Georgia, serif', fontSize: '0.9rem',
    color: '#F2ECDC', minWidth: 20, textAlign: 'center',
  },
  footer: {
    padding: '20px 24px', borderTop: '1px solid rgba(184,144,74,0.18)', flexShrink: 0,
  },
  subtotalRow: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10,
  },
  subtotalLabel: {
    fontFamily: 'Arial, sans-serif', fontSize: '0.65rem', fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: '0.1em', color: 'rgba(242,236,220,0.6)',
  },
  subtotalAmt: {
    fontFamily: 'Georgia, serif', fontSize: '1.1rem', fontWeight: 700, color: '#D4B070',
  },
  note: {
    fontFamily: 'Georgia, serif', fontSize: '0.75rem',
    color: 'rgba(242,236,220,0.3)', lineHeight: 1.55, margin: '0 0 14px', textAlign: 'center',
  },
  checkoutBtn: {
    width: '100%', background: '#B8904A', color: '#1A1A1A', border: 'none', padding: '13px',
    fontFamily: 'Arial, sans-serif', fontSize: '0.65rem', fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: '0.18em',
    cursor: 'pointer', transition: 'background 0.2s',
  },
};

const chkSt = {
  overlay: {
    position: 'fixed', inset: 0, background: 'rgba(26,26,26,0.78)',
    zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 16, transition: 'opacity 0.3s',
  },
  modal: {
    background: '#1A1A1A', border: '1px solid rgba(184,144,74,0.28)',
    width: '100%', maxWidth: 520, maxHeight: '90vh', overflowY: 'auto',
    padding: '40px', position: 'relative',
  },
  closeBtn: {
    position: 'absolute', top: 16, right: 20, background: 'none', border: 'none',
    color: 'rgba(242,236,220,0.35)', fontSize: '1.3rem', cursor: 'pointer', transition: 'color 0.18s',
  },
  title: {
    fontFamily: 'Georgia, serif', fontSize: '1.5rem', fontWeight: 700,
    color: '#F2ECDC', margin: '0 0 6px',
  },
  sub: {
    fontFamily: 'Georgia, serif', fontSize: '0.82rem',
    color: 'rgba(242,236,220,0.4)', margin: '0 0 24px', lineHeight: 1.55,
  },
  toggle: {
    display: 'grid', gridTemplateColumns: '1fr 1fr',
    border: '1px solid rgba(184,144,74,0.28)', marginBottom: 20,
  },
  toggleBtn: {
    padding: '11px', textAlign: 'center', cursor: 'pointer',
    background: 'transparent', border: 'none', borderRight: '1px solid rgba(184,144,74,0.28)',
    color: 'rgba(242,236,220,0.45)', fontFamily: 'Arial, sans-serif',
    fontSize: '0.63rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.12em',
    transition: 'all 0.2s',
  },
  toggleActive: { background: '#B8904A', color: '#1A1A1A' },
  summary: {
    background: 'rgba(242,236,220,0.04)', border: '1px solid rgba(184,144,74,0.15)',
    padding: '14px 16px', marginBottom: 20,
  },
  summaryLabel: {
    fontFamily: 'Arial, sans-serif', fontSize: '0.58rem', fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: '0.16em', color: '#B8904A', margin: '0 0 10px',
  },
  summaryItem: {
    display: 'flex', justifyContent: 'space-between',
    fontFamily: 'Georgia, serif', fontSize: '0.85rem',
    color: 'rgba(242,236,220,0.6)', padding: '3px 0',
  },
  summaryTotal: {
    display: 'flex', justifyContent: 'space-between',
    fontFamily: 'Georgia, serif', fontSize: '0.95rem', fontWeight: 700,
    color: '#F2ECDC', padding: '8px 0 0', marginTop: 6,
    borderTop: '1px solid rgba(184,144,74,0.2)',
  },
  fg: { marginBottom: 14 },
  lbl: {
    display: 'block', fontFamily: 'Arial, sans-serif', fontSize: '0.57rem', fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: '0.16em', color: '#B8904A', marginBottom: 6,
  },
  input: {
    width: '100%', background: 'rgba(242,236,220,0.05)',
    border: '1px solid rgba(184,144,74,0.28)', color: '#F2ECDC',
    padding: '10px 12px', fontFamily: 'Georgia, serif', fontSize: '0.87rem',
    outline: 'none', boxSizing: 'border-box',
  },
  submitBtn: {
    width: '100%', background: '#B8904A', color: '#1A1A1A', border: 'none',
    padding: '13px', marginTop: 4,
    fontFamily: 'Arial, sans-serif', fontSize: '0.65rem', fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: '0.18em',
    cursor: 'pointer', transition: 'background 0.2s',
  },
  successWrap: { textAlign: 'center', padding: '24px 0' },
  successStar: { fontFamily: 'Arial, sans-serif', color: '#B8904A', fontSize: '1.5rem', margin: '0 0 16px' },
  successTitle: {
    fontFamily: 'Georgia, serif', fontSize: '1.4rem', fontWeight: 700,
    color: '#F2ECDC', margin: '0 0 12px',
  },
  successBody: {
    fontFamily: 'Georgia, serif', fontSize: '0.9rem',
    color: 'rgba(242,236,220,0.55)', lineHeight: 1.65,
  },
};

Object.assign(window, { DGCart, DGCheckout });
