// ZION CartDrawer — right-side cart panel with quantities + Shopify checkout
function CartDrawer({ open, items, onClose, onRemove, onQty }) {
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const subtotal = items.reduce((s, i) => s + i.price * (i.qty || 1), 0);

  // ---- On-site offers (these mirror the Shopify rules so checkout matches) ----
  const BOGO_ID = 'freestyle-football';   // Freestyle Ball
  const BOGO_GROUP = 4;                    // buy 3, get 1 free → every 4th ball is free
  const ballItems = items.filter(i => i.id === BOGO_ID);
  const ballQty = ballItems.reduce((n, i) => n + (i.qty || 1), 0);
  const ballUnit = ballItems[0] ? ballItems[0].price : 39;
  const freeBalls = ballQty >= BOGO_GROUP ? 1 : 0;  // one free ball total (buy 3 get 1)
  const bulkDiscount = freeBalls * ballUnit;
  const afterDiscount = subtotal - bulkDiscount;

  // Headless Shopify checkout: build a Shopify cart from the bag, then send the
  // shopper to Shopify's hosted checkout (payments, shipping, tax, order emails).
  const handleCheckout = async () => {
    setErr('');
    const cfg = window.ZION_SHOPIFY;
    if (!cfg || !cfg.domain || !cfg.storefrontToken) {
      setErr('Checkout not connected yet.');
      return;
    }
    const variantIds = cfg.variantIds || {};
    const lines = [];
    const missing = [];
    items.forEach(i => {
      const merchandiseId = variantIds[i.id];
      if (!merchandiseId) { missing.push(i.name); return; }
      lines.push({ merchandiseId, quantity: i.qty || 1 });
    });
    if (missing.length) {
      setErr('These items aren’t linked to the store yet: ' + missing.join(', '));
      return;
    }

    const query = `mutation cartCreate($lines: [CartLineInput!]!) {
      cartCreate(input: { lines: $lines }) {
        cart { checkoutUrl }
        userErrors { field message }
      }
    }`;

    try {
      setBusy(true);
      const r = await fetch(`https://${cfg.domain}/api/${cfg.apiVersion || '2026-01'}/graphql.json`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Shopify-Storefront-Access-Token': cfg.storefrontToken,
        },
        body: JSON.stringify({ query, variables: { lines } }),
      });
      const data = await r.json();
      const url = data && data.data && data.data.cartCreate && data.data.cartCreate.cart && data.data.cartCreate.cart.checkoutUrl;
      const userErrors = data && data.data && data.data.cartCreate && data.data.cartCreate.userErrors;
      if (url) { window.location.href = url; }
      else { setErr((userErrors && userErrors[0] && userErrors[0].message) || 'Could not start checkout.'); setBusy(false); }
    } catch (e) {
      setErr('Could not reach checkout. Check your connection.');
      setBusy(false);
    }
  };

  return (
    <>
      {/* Scrim */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
        backdropFilter: 'blur(4px)', zIndex: 100,
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 220ms',
      }} />
      {/* Panel */}
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 440, maxWidth: '90vw',
        background: 'linear-gradient(180deg, #141210 0%, #0A0A0A 100%)', color: '#fff', zIndex: 101,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform 320ms cubic-bezier(0.16,1,0.3,1)',
        display: 'flex', flexDirection: 'column',
        borderLeft: '1px solid rgba(247,89,31,0.25)',
        boxShadow: '-16px 0 60px rgba(0,0,0,0.55)',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '22px 24px', borderBottom: '1px solid rgba(255,255,255,0.12)',
        }}>
          <div style={{
            fontFamily: 'Poppins', fontWeight: 900, fontStyle: 'italic',
            textTransform: 'uppercase', letterSpacing: '-0.01em', fontSize: 26, color: '#fff',
          }}>YOUR BAG / <span style={{ color: '#F7591F' }}>{items.reduce((n,i)=>n+(i.qty||1),0)}</span></div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: 'Poppins', fontWeight: 800, fontSize: 18, color: 'rgba(255,255,255,0.7)',
          }}>✕</button>
        </div>

        {/* Items */}
        <div style={{ flex: 1, overflow: 'auto', padding: '8px 24px' }}>
          {items.length === 0 ? (
            <div style={{ padding: '64px 0', textAlign: 'center' }}>
              <div style={{
                fontFamily: 'Poppins', fontWeight: 900, fontStyle: 'italic',
                textTransform: 'uppercase', fontSize: 32, lineHeight: 1, marginBottom: 12,
              }}>NOTHING HERE YET.</div>
              <div style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 14, color: 'rgba(255,255,255,0.6)' }}>
                Your bag is cold. Go warm it up.
              </div>
            </div>
          ) : items.map((item, i) => (
            <div key={item.key || i} style={{
              display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 14,
              padding: '18px 0', borderBottom: '1px solid rgba(255,255,255,0.12)',
            }}>
              <div style={{
                aspectRatio: '1/1', background: item.bg, overflow: 'hidden',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {item.img ? (
                  <img src={item.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                ) : (
                  <img src={item.logo} alt="" style={{
                    width: '70%', filter: item.invert ? 'brightness(0) invert(1)' : 'none', opacity: 0.95
                  }} />
                )}
              </div>
              <div>
                <div style={{
                  fontFamily: 'Helvetica Neue, Arial', fontWeight: 700, fontSize: 12,
                  letterSpacing: '0.12em', textTransform: 'uppercase',
                }}>{item.name}</div>
                <div style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 11, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>
                  Size {item.size} · {item.sub}
                </div>
                {/* Qty stepper */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginTop: 10 }}>
                  <Stepper onClick={() => onQty(i, -1)}>−</Stepper>
                  <span style={{
                    fontFamily: 'JetBrains Mono', fontSize: 13, fontWeight: 700,
                    minWidth: 30, textAlign: 'center',
                  }}>{item.qty || 1}</span>
                  <Stepper onClick={() => onQty(i, +1)}>+</Stepper>
                  <button onClick={() => onRemove(i)} style={{
                    marginLeft: 14, background: 'none', border: 'none', padding: 0, cursor: 'pointer',
                    fontFamily: 'Poppins', fontWeight: 700, fontSize: 10, letterSpacing: '0.14em',
                    textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)', textDecoration: 'underline',
                  }}>REMOVE</button>
                </div>
              </div>
              <div style={{ fontFamily: 'JetBrains Mono', fontSize: 13, fontWeight: 700 }}>
                ${item.price * (item.qty || 1)}
              </div>
            </div>
          ))}
        </div>

        {/* Footer */}
        {items.length > 0 && (
          <div style={{ padding: 24, borderTop: '1px solid rgba(255,255,255,0.12)', background: 'rgba(0,0,0,0.28)' }}>

            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>Subtotal</span>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 14, fontWeight: 700 }}>${subtotal}.00</span>
            </div>

            {freeBalls > 0 && (
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 13, color: '#F7591F' }}>Buy 3 get 1 free · {freeBalls} ball{freeBalls > 1 ? 's' : ''} free</span>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 14, fontWeight: 700, color: '#F7591F' }}>−${bulkDiscount}.00</span>
              </div>
            )}

            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
              <span style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>Shipping <span style={{ color: 'rgba(255,255,255,0.45)' }}>· US &amp; EU</span></span>
              <span style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#36C26A' }}>FREE</span>
            </div>

            {err && (
              <div style={{
                fontFamily: 'Poppins', fontWeight: 500, fontSize: 12, color: '#FF7A66',
                marginBottom: 12, lineHeight: 1.5,
              }}>{err}</div>
            )}
            <button onClick={handleCheckout} disabled={busy} style={{
              width: '100%', background: busy ? '#C8420E' : '#F7591F', color: '#fff', border: 'none',
              padding: '18px', cursor: busy ? 'wait' : 'pointer',
              fontFamily: 'Poppins', fontWeight: 800, fontSize: 14, letterSpacing: '0.16em',
              textTransform: 'uppercase', borderRadius: 2,
              boxShadow: '0 10px 30px rgba(247,89,31,0.4), 4px 4px 0 0 rgba(247,89,31,0.25)',
            }}>{busy ? 'OPENING CHECKOUT…' : `CHECKOUT · $${afterDiscount}.00`}</button>
          </div>
        )}
      </aside>
    </>
  );
}

function Stepper({ children, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 28, height: 28, borderRadius: '50%',
      border: '1.5px solid rgba(255,255,255,0.4)', background: 'transparent', cursor: 'pointer',
      fontFamily: 'Poppins', fontWeight: 800, fontSize: 16, lineHeight: 1,
      display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
    }}>{children}</button>
  );
}

window.CartDrawer = CartDrawer;
