// ZION ProductDetail — PDP (dark theme)
// Gallery + quantity + Description/Shipping/Payment accordions, modelled on
// thefireballguy.com product pages but in the ZION look. Add-to-Cart feeds the
// cart drawer, which checks out through Shopify.

// Shared store-wide policy copy (same on every product). Edit here to change everywhere.
const ZION_SHIPPING_COPY = [
  'Free shipping across the US & EU on every order.',
  'Processing time: 1–3 business days after payment.',
  'Freestyle Ball: 2–3 weeks. Fireball: 4–6 weeks.',
];
const ZION_PAYMENT_COPY = [
  'Secure checkout via credit card, Apple Pay, and more.',
  'All transactions are encrypted to protect your privacy and safety.',
];

function ProductDetail({ product, onAdd, onBack, variantIndex }) {
  const PaymentBadges = window.PaymentBadges;
  const sizes = (product.sizes && product.sizes.length) ? product.sizes : ['ONE SIZE'];
  const variants = product.variants || null;
  const colors = variants ? variants.map(v => v.color) : [];
  const [size, setSize] = React.useState(sizes.length > 1 ? sizes[Math.floor(sizes.length / 2)] : sizes[0]);
  const [colorIdx, setColorIdx] = React.useState(variantIndex || 0);
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);
  const [openAcc, setOpenAcc] = React.useState('desc'); // description open by default
  const [requestOpen, setRequestOpen] = React.useState(false); // "By request" modal

  // Gallery: explicit gallery → variant images → [front, back]
  const galleryImgs = (product.gallery && product.gallery.length)
    ? product.gallery
    : (variants ? variants.map(v => v.img) : [product.img, product.img2].filter(Boolean));
  const [activeImg, setActiveImg] = React.useState(0);
  const activeItem = variants ? variants[colorIdx].img : (galleryImgs[activeImg] || galleryImgs[0]);
  const activeIsVideo = activeItem && typeof activeItem === 'object' && !!activeItem.video;
  const mainImg = activeIsVideo ? activeItem.poster : activeItem;

  const isPreorder = product.tag === 'PRE-ORDER';
  const descLines = Array.isArray(product.desc) ? product.desc : (product.desc ? [product.desc] : [product.sub || '']);

  // Live stock from Shopify (needs the inventory scope + quantity tracking enabled).
  const LOW_STOCK = 20;
  const [stock, setStock] = React.useState(null);
  React.useEffect(() => {
    const cfg = window.ZION_SHOPIFY;
    const vid = cfg && cfg.variantIds && cfg.variantIds[product.id];
    if (!cfg || !vid) { setStock(null); return; }
    let cancelled = false;
    const query = 'query($id:ID!){ node(id:$id){ ... on ProductVariant { availableForSale quantityAvailable } } }';
    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: { id: vid } }),
    }).then(r => r.json()).then(d => {
      if (cancelled) return;
      const n = d && d.data && d.data.node;
      if (n) setStock({ qty: (typeof n.quantityAvailable === 'number') ? n.quantityAvailable : null, available: n.availableForSale });
    }).catch(() => {});
    return () => { cancelled = true; };
  }, [product.id]);

  const stockLine = (() => {
    if (!stock) return null;
    if (stock.available === false || stock.qty === 0) return { text: 'Sold out', color: '#C8420E' };
    if (stock.qty != null && stock.qty > 0 && stock.qty < LOW_STOCK) return { text: `Only ${stock.qty} left in stock, order soon`, color: '#F7591F' };
    return null;
  })();

  // On-site offer hint (the actual discount/free-shipping are enforced by Shopify).
  const offerHints = product.byRequest ? []
    : (product.id === 'freestyle-football'
      ? ['Buy 3, get 1 free', 'Free shipping across US & EU']
      : ['Free shipping across US & EU']);

  // Reflect the buy-3-get-1-free deal live in the Add-to-bag total.
  const BOGO_GROUP = 4; // buy 3, get 1 free → ONE free ball total at 4+ (not repeating)
  const isFsb = product.id === 'freestyle-football';
  const freeUnits = (isFsb && qty >= BOGO_GROUP) ? 1 : 0;
  // The qty stepper SKIPS the value 3 so picking 3 lands on 4 (3 paid + 1 free).
  // Only ONE free ball — past 4 the stepper steps normally (5, 6, 7, 8 …).
  const incQty = (q) => { if (!isFsb) return q + 1; const n = q + 1; return n === 3 ? 4 : n; };
  const decQty = (q) => { if (!isFsb) return Math.max(1, q - 1); const n = Math.max(1, q - 1); return n === 3 ? 2 : n; };
  const lineTotal = product.price * qty;
  const bulkOnPDP = freeUnits > 0;
  const shownTotal = lineTotal - freeUnits * product.price;

  const handleAdd = () => {
    onAdd({ ...product, size, qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1600);
  };

  return (
    <section style={{ padding: '32px 48px 96px', maxWidth: 1280, margin: '0 auto', color: '#fff', position: 'relative' }}>
      <a onClick={onBack} style={{
        cursor: 'pointer', fontFamily: 'Poppins', fontWeight: 700, fontSize: 12,
        letterSpacing: '0.14em', textTransform: 'uppercase', color: '#F7591F',
        display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 28,
      }}>← BACK</a>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'start' }}>
        {/* ---------- GALLERY ---------- */}
        <div>
          <div style={{ position: 'relative' }}>
            <div style={{ aspectRatio: '1/1', width: '100%', overflow: 'hidden', borderRadius: 16, background: product.bg || '#141414', position: 'relative' }}>
              {activeIsVideo ? (
                <GalleryVideo src={activeItem.video} poster={activeItem.poster} />
              ) : (
                <img id="pdp-main-img" src={mainImg} alt={product.name} style={{
                  width: '100%', height: '100%', objectFit: 'cover', display: 'block',
                }} />
              )}
            </div>
            {product.tag && (
              <div style={{
                position: 'absolute', top: 18, left: 18, pointerEvents: 'none',
                fontFamily: 'Poppins', fontWeight: 800, fontStyle: 'italic', fontSize: 13,
                letterSpacing: '0.08em', textTransform: 'uppercase', color: '#fff',
                background: isPreorder ? '#F7591F' : 'rgba(0,0,0,0.5)', border: '1.5px solid #F7591F',
                padding: '6px 11px 4px',
              }}>{product.tag}</div>
            )}
          </div>

          {/* Thumbnails */}
          {galleryImgs.length > 1 && (
            <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
              {galleryImgs.map((it, i) => {
                const vid = it && typeof it === 'object' && it.video;
                const thumb = vid ? it.poster : it;
                return (
                  <button key={i}
                    onClick={() => { setActiveImg(i); if (variants) setColorIdx(i); }}
                    style={{
                      width: 84, aspectRatio: '1/1', padding: 0, cursor: 'pointer', position: 'relative',
                      overflow: 'hidden', background: product.bg || '#141414', borderRadius: 10,
                      border: (variants ? i === colorIdx : i === activeImg) ? '2px solid #F7591F' : '2px solid rgba(255,255,255,0.12)',
                    }}>
                    <img src={thumb} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    {vid && (
                      <span style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
                        <span style={{ width: 26, height: 26, borderRadius: '50%', background: 'rgba(247,89,31,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="#fff" aria-hidden="true"><path d="M8 5v14l11-7z" /></svg>
                        </span>
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* ---------- INFO ---------- */}
        <div style={{ paddingTop: 8 }}>
          {!product.byRequest && product.tag && (
            <div style={{
              fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.22em',
              textTransform: 'uppercase', color: '#F7591F', marginBottom: 10,
            }}>{product.tag}</div>
          )}

          <h1 style={{
            fontFamily: 'Poppins', fontWeight: 900, fontStyle: 'italic',
            textTransform: 'uppercase', letterSpacing: '-0.015em',
            fontSize: 'clamp(34px, 4vw, 56px)', lineHeight: 0.95, margin: 0, color: '#fff',
          }}>{product.name}</h1>

          <div style={{ marginTop: 14, display: 'flex', gap: 14, alignItems: 'baseline' }}>
            {product.byRequest ? (
              <div style={{ fontFamily: 'Poppins', fontSize: 16, fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#F7591F' }}>Sold out</div>
            ) : (
              <div style={{ fontFamily: 'JetBrains Mono', fontSize: 24, fontWeight: 700, color: '#fff' }}>${product.price}.00</div>
            )}
            <div style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 14, color: '#B8B8B8' }}>{product.sub}</div>
          </div>

          {/* Offer hints — one per row */}
          {offerHints.length > 0 && (
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {offerHints.map((h, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 8,
                fontFamily: 'Poppins', fontWeight: 700, fontSize: 12,
                letterSpacing: '0.02em', color: '#F7591F',
              }}>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#F7591F', display: 'inline-block', flexShrink: 0 }} />
                {h}
              </div>
            ))}
          </div>
          )}

          {/* Live stock */}
          {stockLine && (
            <div style={{
              marginTop: 12, display: 'flex', alignItems: 'center', gap: 8,
              fontFamily: 'Poppins', fontWeight: 600, fontSize: 13, color: stockLine.color,
            }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: stockLine.color, display: 'inline-block', flexShrink: 0 }} />
              {stockLine.text}
            </div>
          )}

          {/* Color (only when variants actually swap the image) */}
          {variants && colors.length > 0 && (
            <Section label="Color">
              <div style={{ display: 'flex', gap: 10 }}>
                {colors.map((c, i) => (
                  <button key={c} onClick={() => {
                    setColorIdx(i);
                    const m = document.getElementById('pdp-main-img'); if (m) m.src = variants[i].img;
                  }} style={{
                    width: 32, height: 32, background: c, padding: 0, cursor: 'pointer',
                    border: i === colorIdx ? '2px solid #fff' : '1px solid rgba(255,255,255,0.3)',
                    borderRadius: '50%', outline: i === colorIdx ? '2px solid #F7591F' : 'none', outlineOffset: 2,
                  }} />
                ))}
              </div>
            </Section>
          )}

          {/* Size — picker for multi-size products; single sizes show just the value */}
          {sizes.length > 1 ? (
            <Section label="Size">
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {sizes.map(s => (
                  <button key={s} onClick={() => setSize(s)} style={{
                    fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.1em',
                    textTransform: 'uppercase', cursor: 'pointer', padding: '10px 18px',
                    background: size === s ? '#F7591F' : 'transparent', color: '#fff',
                    border: size === s ? '1.5px solid #F7591F' : '1.5px solid rgba(255,255,255,0.4)', borderRadius: 999,
                  }}>{s}</button>
                ))}
              </div>
            </Section>
          ) : (
            <div style={{
              marginTop: 28,
              fontFamily: 'Poppins', fontWeight: 700, fontSize: 17, letterSpacing: '0.08em',
              textTransform: 'uppercase', color: '#fff',
            }}>{sizes[0]}</div>
          )}

          {/* Sold-out products show "REMIND ME" (waitlist); everything else is buyable */}
          {product.byRequest ? (
            <div style={{ marginTop: 32 }}>
              <FireButton hard onClick={() => setRequestOpen(true)}>SOLD OUT · REMIND ME</FireButton>
              <div style={{ marginTop: 12, fontFamily: 'Poppins', fontWeight: 500, fontSize: 13, lineHeight: 1.55, color: '#B8B8B8', maxWidth: '46ch' }}>
                The Fireball is currently sold out. Leave your details and we'll let you know the moment it's back in stock.
              </div>
            </div>
          ) : (
            <div style={{ marginTop: 32, display: 'flex', gap: 14, alignItems: 'stretch', flexWrap: 'wrap' }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 0,
                border: '1.5px solid rgba(255,255,255,0.4)', borderRadius: 999, padding: '0 6px',
              }}>
                <QtyBtn onClick={() => setQty(decQty)}>−</QtyBtn>
                <span style={{ fontFamily: 'JetBrains Mono', fontSize: 15, fontWeight: 700, minWidth: 34, textAlign: 'center' }}>{qty}</span>
                <QtyBtn onClick={() => setQty(incQty)}>+</QtyBtn>
              </div>
              <FireButton hard onClick={handleAdd}>
                {added ? '✓ ADDED TO BAG' : (isPreorder ? `PRE-ORDER · $${shownTotal}` : `ADD TO BAG · $${shownTotal}`)}
              </FireButton>
            </div>
          )}

          {/* Live bulk-discount confirmation once 5+ balls are selected */}
          {bulkOnPDP && (
            <div style={{ marginTop: 10, fontFamily: 'Poppins', fontWeight: 700, fontSize: 12.5, color: '#1A8F3C' }}>
              ✓ Buy 3 get 1 free · {freeUnits} ball{freeUnits > 1 ? 's' : ''} free ·{' '}
              <span style={{ textDecoration: 'line-through', color: '#8A8A8A', fontWeight: 600 }}>${lineTotal}</span>{' '}
              <span style={{ color: '#fff' }}>${shownTotal}</span>
            </div>
          )}

          {/* Trust line + payments — only for buyable products */}
          {!product.byRequest && (
            <div style={{
              marginTop: 18, display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap',
              fontFamily: 'Poppins', fontWeight: 600, fontSize: 12, letterSpacing: '0.06em', color: '#B8B8B8',
            }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#F7591F" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
                SECURE PAYMENTS
              </span>
              <span>SHIPS TO US &amp; EU</span>
            </div>
          )}

          {!product.byRequest && PaymentBadges && (
            <div style={{ marginTop: 14 }}>
              <PaymentBadges align="flex-start" />
            </div>
          )}

          {/* Accordions */}
          <div style={{ marginTop: 32, borderTop: '1px solid rgba(255,255,255,0.14)' }}>
            <PdpAccordion label="Description" isOpen={openAcc === 'desc'} onToggle={() => setOpenAcc(openAcc === 'desc' ? null : 'desc')} lines={descLines} />
            <PdpAccordion label="Shipping"    isOpen={openAcc === 'ship'} onToggle={() => setOpenAcc(openAcc === 'ship' ? null : 'ship')} lines={product.shipping || ZION_SHIPPING_COPY} />
            <PdpAccordion label="Payment"     isOpen={openAcc === 'pay'}  onToggle={() => setOpenAcc(openAcc === 'pay'  ? null : 'pay')}  lines={product.payment  || ZION_PAYMENT_COPY} />
          </div>
        </div>
      </div>

      {product.reviews && product.reviews.length > 0 && <ProductReviews reviews={product.reviews} />}

      <RequestModal open={requestOpen} product={product} onClose={() => setRequestOpen(false)} />
    </section>
  );
}

function QtyBtn({ children, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 38, height: 44, background: 'transparent', border: 'none', cursor: 'pointer',
      fontFamily: 'Poppins', fontWeight: 800, fontSize: 18, lineHeight: 1, color: '#fff',
    }}>{children}</button>
  );
}

function PdpAccordion({ label, isOpen, onToggle, lines }) {
  return (
    <div style={{ borderBottom: '1px solid rgba(255,255,255,0.14)' }}>
      <button onClick={onToggle} style={{
        width: '100%', background: 'transparent', border: 'none', cursor: 'pointer',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '18px 0', color: '#fff',
      }}>
        <span style={{
          fontFamily: 'Poppins', fontWeight: 700, fontSize: 13, letterSpacing: '0.16em', textTransform: 'uppercase',
        }}>{label}</span>
        <span style={{
          width: 26, height: 26, borderRadius: '50%', position: 'relative', flexShrink: 0,
          border: `1px solid ${isOpen ? '#F7591F' : 'rgba(255,255,255,0.3)'}`,
          background: isOpen ? '#F7591F' : 'transparent',
          transform: isOpen ? 'rotate(135deg)' : 'rotate(0deg)', transition: 'transform 300ms, background 200ms, border-color 200ms',
        }}>
          <span style={{ position: 'absolute', left: '50%', top: '50%', width: 11, height: 2, background: '#fff', transform: 'translate(-50%,-50%)' }} />
          <span style={{ position: 'absolute', left: '50%', top: '50%', width: 2, height: 11, background: '#fff', transform: 'translate(-50%,-50%)' }} />
        </span>
      </button>
      <div style={{ display: 'grid', gridTemplateRows: isOpen ? '1fr' : '0fr', transition: 'grid-template-rows 360ms cubic-bezier(0.16,1,0.3,1)' }}>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ paddingBottom: 20 }}>
            {lines.map((t, i) => (
              <p key={i} style={{
                fontFamily: 'Poppins', fontWeight: 400, fontSize: 15, lineHeight: 1.7,
                color: 'rgba(255,255,255,0.74)', margin: '0 0 8px',
              }}>{t}</p>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={{ marginTop: 28 }}>
      <div style={{
        fontFamily: 'Poppins', fontWeight: 700, fontSize: 11, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: '#B8B8B8', marginBottom: 12,
      }}>{label}</div>
      {children}
    </div>
  );
}

// ===========================================================================
// RequestModal — "By request" form for the Fire Football.
// Collects Name / Email / Location / Age / Product use + a required safety
// disclaimer, then sends it to the contact email (Formspree endpoint if set,
// otherwise opens the visitor's mail app as a fallback).
// ===========================================================================
function RequestModal({ open, product, onClose }) {
  const TO = (typeof window !== 'undefined' && window.ZION_CONTACT_EMAIL) || 'manager@levizion.com';
  const [form, setForm] = React.useState({ name: '', email: '', location: '', age: '', use: '' });
  const [agree, setAgree] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [err, setErr] = React.useState('');
  const upd = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  React.useEffect(() => {
    if (open) { setForm({ name: '', email: '', location: '' }); setAgree(false); setBusy(false); setSent(false); setErr(''); }
  }, [open]);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    if (!agree) { setErr('Please confirm the safety disclaimer to continue.'); return; }
    const endpoint = (typeof window !== 'undefined' && window.ZION_FORM_ENDPOINT) || '';
    const data = {
      _subject: `Fireball · restock reminder from ${form.name}`,
      _template: 'table', _honey: '',
      product: product ? product.name : 'Fireball',
      name: form.name, email: form.email, location: form.location,
      safety_disclaimer_accepted: 'Yes',
    };
    if (endpoint) {
      try {
        setBusy(true);
        const r = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(data) });
        if (r.ok) setSent(true);
        else { setErr('Could not send. Please try again, or email ' + TO); setBusy(false); }
      } catch (e2) { setErr('Could not send. Check your connection.'); setBusy(false); }
    } else {
      const subject = `Fireball · restock reminder from ${form.name}`;
      const body = [
        `Product: ${product ? product.name : 'Fireball'}`,
        `Name: ${form.name}`, `Email: ${form.email}`, `Location: ${form.location}`,
        `Safety disclaimer accepted: Yes`, ``, `via thefireballguy.com`,
      ].join('\n');
      window.location.href = `mailto:${TO}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
      setSent(true);
    }
  };

  const field = {
    width: '100%', boxSizing: 'border-box', background: 'rgba(255,255,255,0.04)',
    border: '1px solid rgba(255,255,255,0.18)', borderRadius: 10, color: '#fff', outline: 'none',
    fontFamily: 'Poppins', fontWeight: 500, fontSize: 15, padding: '13px 15px',
  };
  const label = { fontFamily: 'Poppins', fontWeight: 600, fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.65)', marginBottom: 7, display: 'block' };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(10,10,10,0.9)', backdropFilter: 'blur(10px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '6vh 20px', overflowY: 'auto',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480, position: 'relative',
        background: 'linear-gradient(180deg, #161310 0%, #0A0A0A 100%)',
        border: '1px solid rgba(247,89,31,0.4)', borderRadius: 20, padding: '36px 30px',
        boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          position: 'absolute', top: 16, right: 18, background: 'transparent', border: 'none',
          color: 'rgba(255,255,255,0.6)', fontFamily: 'Poppins', fontWeight: 800, fontSize: 20, cursor: 'pointer',
        }}>✕</button>

        <div style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#F7591F', marginBottom: 8 }}>Sold out · Remind me</div>

        {!sent ? (
          <>
            <h3 style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 900, fontStyle: 'italic', textTransform: 'uppercase', fontSize: 30, lineHeight: 0.98, margin: '0 0 8px', color: '#fff' }}>
              Remind me when it's back
            </h3>
            <p style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 14, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)', margin: '0 0 22px' }}>
              The Fireball is currently sold out. Leave your details and we'll email you the moment it's back in stock. As a real fire prop, we review every request.
            </p>

            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div><span style={label}>Name *</span><input style={field} required value={form.name} onChange={upd('name')} placeholder="Your full name" /></div>
              <div><span style={label}>Email *</span><input type="email" style={field} required value={form.email} onChange={upd('email')} placeholder="you@email.com" /></div>
              <div><span style={label}>Location *</span><input style={field} required value={form.location} onChange={upd('location')} placeholder="City, country" /></div>

              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', marginTop: 2 }}>
                <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} style={{ width: 18, height: 18, marginTop: 2, accentColor: '#F7591F', flexShrink: 0 }} />
                <span style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 12.5, lineHeight: 1.5, color: 'rgba(255,255,255,0.72)' }}>
                  <strong style={{ color: '#fff' }}>Safety disclaimer:</strong> I understand the Fireball involves real, open flame and inherent risk. I confirm I am of legal age to handle fire equipment where I live, and I agree to follow all ZION safety guidelines and assume full responsibility for its use.
                </span>
              </label>

              {err && <div style={{ fontFamily: 'Poppins', fontWeight: 500, fontSize: 12.5, color: '#FF7A66', lineHeight: 1.5 }}>{err}</div>}

              <button type="submit" disabled={busy} style={{
                width: '100%', background: busy ? '#C8420E' : '#F7591F', color: '#fff', border: 'none',
                fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase',
                padding: '16px 0', cursor: busy ? 'wait' : 'pointer', borderRadius: 999, boxShadow: '0 8px 24px rgba(247,89,31,0.32)', marginTop: 4,
              }}>{busy ? 'Sending…' : 'Notify me'}</button>
            </form>
          </>
        ) : (
          <>
            <h3 style={{ fontFamily: 'Poppins, sans-serif', fontWeight: 900, fontStyle: 'italic', textTransform: 'uppercase', fontSize: 30, lineHeight: 0.98, margin: '0 0 10px', color: '#fff' }}>
              You're on the list.
            </h3>
            <p style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 14, lineHeight: 1.6, color: 'rgba(255,255,255,0.7)', margin: '0 0 24px' }}>
              Thanks{form.name ? ', ' + form.name : ''}. We'll email <span style={{ color: '#F7591F', fontWeight: 600 }}>{form.email || 'you'}</span> the moment the Fireball is back in stock. Stay lit.
            </p>
            <button onClick={onClose} style={{
              width: '100%', background: 'transparent', color: '#fff', border: '1.5px solid rgba(255,255,255,0.4)',
              fontFamily: 'Poppins', fontWeight: 800, fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase',
              padding: '16px 0', cursor: 'pointer', borderRadius: 999,
            }}>Done</button>
          </>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   GalleryVideo — small muted poster with a play badge; click to
   enlarge into a cinema overlay that plays with sound (like Story).
   ============================================================ */
function GalleryVideo({ src, poster }) {
  const [open, setOpen] = React.useState(false);
  const vref = React.useRef(null);

  const openCinema = () => { setOpen(true); document.body.style.overflow = 'hidden'; };
  const close = () => {
    const v = vref.current; if (v) v.pause();
    setOpen(false); document.body.style.overflow = '';
  };

  React.useEffect(() => {
    if (!open) return;
    const v = vref.current;
    if (v) { v.muted = false; try { v.currentTime = 0; } catch (e) {} v.play().catch(() => {}); }
    const onKey = (e) => { if (e.key === 'Escape') close(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  return (
    <>
      {/* Small clickable poster + play badge (muted, not playing) */}
      <div onClick={openCinema} style={{ position: 'absolute', inset: 0, cursor: 'zoom-in' }}>
        <img src={poster} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.22)' }} />
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div style={{ width: 66, height: 66, borderRadius: '50%', background: 'rgba(247,89,31,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 10px 34px rgba(247,89,31,0.5)' }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="#fff" aria-hidden="true"><path d="M8 5v14l11-7z" /></svg>
          </div>
        </div>
        <div style={{ position: 'absolute', bottom: 12, left: 12, display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'Poppins', fontWeight: 700, fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#fff', background: 'rgba(0,0,0,0.5)', padding: '6px 11px', borderRadius: 999, border: '1px solid rgba(255,255,255,0.25)', pointerEvents: 'none' }}>
          <span style={{ fontSize: 10 }}>▶</span> Watch
        </div>
      </div>

      {/* Cinema overlay — portal to body so it covers the whole screen */}
      {ReactDOM.createPortal(
        <div onClick={close} style={{
          position: 'fixed', inset: 0, zIndex: 200,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '5vw',
          background: 'rgba(6,4,2,0.8)', backdropFilter: 'blur(18px)', WebkitBackdropFilter: 'blur(18px)',
          opacity: open ? 1 : 0, visibility: open ? 'visible' : 'hidden',
          transition: 'opacity 360ms ease, visibility 360ms', cursor: 'zoom-out',
        }}>
          <video
            ref={vref} src={src} poster={poster} playsInline controls preload="none"
            onClick={(e) => e.stopPropagation()}
            style={{
              maxWidth: 'min(92vw, 460px)', maxHeight: '86vh', width: 'auto', height: 'auto',
              borderRadius: 14, background: '#000',
              boxShadow: '0 0 0 2px rgba(247,89,31,0.85), 0 0 60px rgba(247,89,31,0.5)',
            }}
          />
          <button onClick={close} aria-label="Close" style={{
            position: 'fixed', top: 20, right: 24, width: 46, height: 46, borderRadius: '50%',
            background: 'rgba(0,0,0,0.5)', border: '1px solid rgba(255,255,255,0.3)', color: '#fff',
            fontFamily: 'Poppins', fontWeight: 800, fontSize: 20, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>✕</button>
        </div>,
        document.body
      )}
    </>
  );
}

/* ============================================================
   Reviews — fire-rated testimonial cards (themed for ZION)
   ============================================================ */
function FireRating({ rating = 5, size = 16 }) {
  return (
    <span style={{ display: 'inline-flex', gap: 2, lineHeight: 1, color: '#F7591F', filter: 'drop-shadow(0 0 6px rgba(247,89,31,0.45))' }}>
      {Array.from({ length: rating }).map((_, i) => (
        <span key={i} style={{ fontSize: size }}>★</span>
      ))}
    </span>
  );
}

function VerifiedTick() {
  return (
    <span style={{
      width: 16, height: 16, borderRadius: '50%', background: '#F7591F',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>
      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M5 12l5 5L20 6" />
      </svg>
    </span>
  );
}

function ReviewCard({ r }) {
  const [hover, setHover] = React.useState(false);
  const initial = (r.name || '?').trim().charAt(0).toUpperCase();
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        width: '100%', maxWidth: 320, background: 'linear-gradient(180deg, #171310 0%, #0E0D0C 100%)',
        border: `1px solid ${hover ? 'rgba(247,89,31,0.45)' : 'rgba(255,255,255,0.08)'}`,
        borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column',
        transform: hover ? 'translateY(-4px)' : 'translateY(0)',
        boxShadow: hover ? '0 20px 46px rgba(247,89,31,0.16)' : '0 10px 28px rgba(0,0,0,0.4)',
        transition: 'transform 320ms cubic-bezier(0.16,1,0.3,1), box-shadow 320ms, border-color 280ms',
      }}>
      {/* Photo / themed avatar */}
      <div style={{
        position: 'relative', aspectRatio: '1 / 1',
        background: r.img ? '#000' : 'radial-gradient(ellipse 90% 80% at 50% 25%, #3A0F08 0%, #1A0A06 60%, #141210 100%)',
      }}>
        {r.img
          ? <img src={r.img} alt={r.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : <div style={{
              position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-script)', fontStyle: 'italic', fontSize: 72, color: 'rgba(247,89,31,0.92)',
              textShadow: '0 0 26px rgba(247,89,31,0.5)',
            }}>{initial}</div>
        }
        {/* fire-rating chip overlapping the bottom edge */}
        <div style={{
          position: 'absolute', left: '50%', bottom: -15, transform: 'translateX(-50%)',
          background: '#0A0A0A', border: '1px solid rgba(247,89,31,0.5)', borderRadius: 999,
          padding: '7px 14px', boxShadow: '0 8px 20px rgba(0,0,0,0.55)', whiteSpace: 'nowrap',
        }}>
          <FireRating rating={r.rating || 5} size={15} />
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: '28px 22px 24px', textAlign: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, marginBottom: 12 }}>
          <span style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 15, color: '#fff' }}>
            {r.name}{r.location ? <span style={{ color: 'rgba(255,255,255,0.5)', fontWeight: 500 }}> · {r.location}</span> : null}
          </span>
          {r.verified && <VerifiedTick />}
        </div>
        <p style={{ fontFamily: 'Poppins', fontWeight: 400, fontSize: 14, lineHeight: 1.6, color: 'rgba(255,255,255,0.8)', margin: 0 }}>
          {r.text}
        </p>
      </div>
    </div>
  );
}

function ProductReviews({ reviews }) {
  return (
    <div style={{ marginTop: 76 }}>
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <div style={{
          fontFamily: 'Poppins', fontWeight: 700, fontSize: 12, letterSpacing: '0.22em',
          textTransform: 'uppercase', color: '#F7591F', marginBottom: 10,
        }}>Reviews</div>
        <h2 style={{
          fontFamily: 'var(--font-script)', fontStyle: 'italic', textTransform: 'uppercase',
          fontSize: 'clamp(40px, 6vw, 76px)', lineHeight: 0.95, margin: 0, color: '#fff',
        }}>What ballers say</h2>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, justifyContent: 'center' }}>
        {reviews.map((r, i) => <ReviewCard key={i} r={r} />)}
      </div>
    </div>
  );
}

window.ProductDetail = ProductDetail;
