/* ── Product Detail — Slide-in Overlay Panel ── */

/* ─── Scent Catalogue ─── */
const SPECIAL_SCENTS = [
  { name: 'Vitality',            notes: 'Cypress · Grapefruit · Helichrysum' },
  { name: 'Focus',               notes: 'Lemon · Rosemary · Basil' },
  { name: 'Refresh',             notes: 'Eucalyptus · Lemon Eucalyptus · Spearmint' },
  { name: 'Clean Air',           notes: 'Oregano · Tea Tree · Lemon' },
  { name: 'Forget Your Trouble', notes: 'Clary Sage · Grapefruit · Tangerine' },
  { name: 'Peaceful Evening',    notes: 'Myrrh · Sandalwood · Lavender' },
  { name: 'Relaxing Bloom',      notes: 'Lavender · Geranium · Tea Tree' },
  { name: 'Breathe Well',        notes: 'Peppermint · Turmeric · Frankincense' },
  { name: 'Inner Peace',         notes: 'Chamomile · Lavender · Vetiver · Cedarwood' },
  { name: 'Sweet Night',         notes: 'Juniper Berry · Bergamot · Vetiver · Copaiba' },
  { name: 'Sweetest Musk',       notes: 'Ylang Ylang · Sandalwood · Vanilla' },
  { name: 'Happy Mood',          notes: 'Jasmine · Neroli · Bergamot' },
  { name: 'Cozy In Spring',      notes: 'Chamomile · Sweet Orange · Vetiver' },
  { name: 'Ocean Mist',          notes: 'Spearmint · Peppermint · Citronella' },
  { name: 'Forest Romance',      notes: 'Sandalwood · Cypress · Patchouli · Bergamot' },
  { name: 'Energy Boost',        notes: 'Sweet Orange · Peppermint · Lemongrass · Spearmint' },
];

const SINGLE_SCENT_NAMES = [
  'Basil', 'Bergamot', 'Cedarwood', 'Chamomile', 'Citronella', 'Clary Sage',
  'Copaiba', 'Cypress', 'Eucalyptus', 'Frankincense', 'Geranium', 'Grapefruit',
  'Helichrysum', 'Jasmine', 'Juniper Berry', 'Lavender', 'Lemon',
  'Lemon Eucalyptus', 'Lemongrass', 'Myrrh', 'Neroli', 'Oregano', 'Patchouli',
  'Peppermint', 'Rose', 'Rosemary', 'Sandalwood', 'Spearmint', 'Sweet Orange',
  'Tangerine', 'Tea Tree', 'Turmeric', 'Vanilla', 'Vetiver', 'Ylang Ylang',
].sort();

function getScentAdj(name) {
  if (!name || name === 'Unscented') return 0;
  return SPECIAL_SCENTS.some(s => s.name === name) ? 2 : 1;
}

function getScentNotes(name) {
  if (!name || name === 'Unscented') return null;
  const sp = SPECIAL_SCENTS.find(s => s.name === name);
  return sp ? sp.notes : null;
}

/* ─── Quantity Drum Wheel ─── */
function QtyWheel({ qty, setQty, bulk, setBulk }) {
  const inc = React.useCallback(() => {
    if (bulk) return;
    if (qty >= 50) { setBulk(true); return; }
    setQty(qty + 1);
  }, [qty, bulk]);

  const dec = React.useCallback(() => {
    if (bulk) { setBulk(false); return; }
    if (qty > 1) setQty(qty - 1);
  }, [qty, bulk]);

  /* Mouse wheel: scroll UP = increase, scroll DOWN = decrease */
  const wheelRef = React.useRef(null);
  React.useEffect(() => {
    const handler = (e) => { e.preventDefault(); e.deltaY < 0 ? inc() : dec(); };
    const el = wheelRef.current;
    if (!el) return;
    el.addEventListener('wheel', handler, { passive: false });
    return () => el.removeEventListener('wheel', handler);
  }, [inc, dec]);

  const cur  = bulk ? '50+' : String(qty);
  const prev = bulk ? ''    : (qty < 50 ? String(qty + 1) : '50+'); /* item above = higher */
  const next = bulk ? '50'  : (qty > 1  ? String(qty - 1) : '');  /* item below = lower  */

  return React.createElement('div', { ref: wheelRef, className: 'cc-qty-wheel' },
    /* Up arrow — INCREASES quantity */
    React.createElement('button', {
      className: 'cc-qty-arrow',
      onClick: inc,
      disabled: bulk,
      'aria-label': 'Increase quantity',
    },
      React.createElement('svg', { width: 14, height: 9, viewBox: '0 0 14 9', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' },
        React.createElement('polyline', { points: '1,7 7,2 13,7' }),
      ),
    ),
    /* Drum window */
    React.createElement('div', { className: 'cc-qty-window' },
      React.createElement('div', { className: 'cc-qty-item cc-qty-prev' }, prev),
      React.createElement('div', { className: 'cc-qty-item cc-qty-cur', 'aria-live': 'polite' }, cur),
      React.createElement('div', { className: 'cc-qty-item cc-qty-next' }, next),
    ),
    /* Down arrow — DECREASES quantity */
    React.createElement('button', {
      className: 'cc-qty-arrow',
      onClick: dec,
      disabled: !bulk && qty <= 1,
      'aria-label': 'Decrease quantity',
    },
      React.createElement('svg', { width: 14, height: 9, viewBox: '0 0 14 9', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' },
        React.createElement('polyline', { points: '1,2 7,7 13,2' }),
      ),
    ),
  );
}

/* ─── Main Overlay ─── */
function ProductOverlay({ product, cart, setCart, onClose }) {
  const basePrice = product.salePrice || product.price;

  const [color,        setColor]        = React.useState((product.colors || [])[0] || '');
  const [scent,        setScent]        = React.useState('Unscented');
  const [size,         setSize]         = React.useState((product.sizes || [])[0] || '');
  const [qty,          setQty]          = React.useState(1);
  const [bulk,         setBulk]         = React.useState(false);
  const [personalName, setPersonalName] = React.useState('');
  const [added,        setAdded]        = React.useState(false);
  const [visible,      setVisible]      = React.useState(false);

  const scentAdj  = getScentAdj(scent);
  const scentNote = getScentNotes(scent);
  const unitPrice = basePrice + scentAdj;
  const totalPrice = bulk ? null : unitPrice * qty;

  /* Animate in */
  React.useEffect(() => { const t = setTimeout(() => setVisible(true), 20); return () => clearTimeout(t); }, []);

  /* Lock scroll */
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  /* ESC key */
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') handleClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  const handleClose = () => { setVisible(false); setTimeout(onClose, 420); };

  const addToCart = () => {
    setCart([...cart, {
      ...product,
      selectedColor: color,
      selectedScent: scent,
      selectedSize:  size,
      selectedQty:   bulk ? '50+' : qty,
      personalName:  personalName || null,
      unitPrice,
      totalPrice,
    }]);
    setAdded(true);
    setTimeout(() => { setAdded(false); handleClose(); }, 1000);
  };

  return React.createElement(React.Fragment, null,
    /* Backdrop */
    React.createElement('div', {
      className: 'cc-overlay-backdrop' + (visible ? ' visible' : ''),
      onClick: handleClose,
    }),

    /* Drawer panel */
    React.createElement('div', { className: 'cc-overlay-panel' + (visible ? ' visible' : '') },

      /* Close button */
      React.createElement('button', { className: 'cc-overlay-close', onClick: handleClose, 'aria-label': 'Close panel' },
        React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 },
          React.createElement('path', { d: 'M18 6L6 18M6 6l12 12' }),
        ),
      ),

      React.createElement('div', { className: 'cc-overlay-inner' },

        /* ── Left: image gallery ── */
        React.createElement('div', { className: 'cc-overlay-gallery' },
          React.createElement('div', { className: 'cc-overlay-img' },
            React.createElement(CandlePlaceholder, { product, large: true }),
            color && React.createElement('div', {
              className: 'cc-color-preview',
              style: { background: COLOR_SWATCHES[color] || 'transparent' },
            }),
          ),
          React.createElement('div', { className: 'cc-overlay-thumbs' },
            [0, 1, 2].map(i =>
              React.createElement('div', {
                key: i,
                className: 'cc-overlay-thumb' + (i === 0 ? ' active' : ''),
              },
                React.createElement(CandlePlaceholder, { product }),
              )
            ),
          ),
        ),

        /* ── Right: detail + all options ── */
        React.createElement('div', { className: 'cc-overlay-detail' },

          /* Header */
          React.createElement('p', { className: 'cc-eyebrow' }, product.subtitle),
          React.createElement('h2', { className: 'cc-pd-title' }, product.name),

          /* Pricing row */
          React.createElement('div', { className: 'cc-pd-pricing' },
            product.salePrice
              ? React.createElement(React.Fragment, null,
                  React.createElement('span', { className: 'cc-pd-price-sale' }, '$' + product.salePrice.toFixed(2)),
                  React.createElement('span', { className: 'cc-pd-price-orig' }, '$' + product.price.toFixed(2)),
                )
              : React.createElement('span', { className: 'cc-pd-price-sale' }, '$' + product.price.toFixed(2)),
            scentAdj > 0 && React.createElement('span', { className: 'cc-pd-scent-adj' },
              '+ $' + scentAdj.toFixed(2) + (scentAdj === 2 ? ' blend' : ' scent'),
            ),
          ),

          React.createElement('p', { className: 'cc-pd-desc' }, product.description),

          React.createElement('div', { className: 'cc-options-divider' }),

          /* ── Options ── */
          React.createElement('div', { className: 'cc-options-list' },

            /* Color */
            product.colors && product.colors.length > 0 &&
              React.createElement('div', { className: 'cc-option-row' },
                React.createElement('p', { className: 'cc-option-label' },
                  'Color',
                  React.createElement('span', { className: 'cc-option-cur' }, color),
                ),
                React.createElement('div', { className: 'cc-color-swatches' },
                  product.colors.map(c =>
                    React.createElement('button', {
                      key: c,
                      className: 'cc-swatch-btn' + (c === color ? ' selected' : ''),
                      onClick: () => setColor(c),
                      title: c,
                      'aria-label': c,
                      'aria-pressed': c === color,
                    },
                      React.createElement('span', {
                        className: 'cc-swatch-circle',
                        style: { background: COLOR_SWATCHES[c] || '#ccc' },
                      }),
                      React.createElement('span', { className: 'cc-swatch-name' }, c),
                    )
                  ),
                ),
              ),

            /* Scent */
            React.createElement('div', { className: 'cc-option-row' },
              React.createElement('p', { className: 'cc-option-label' },
                'Scent',
                scentAdj > 0 && React.createElement('span', { className: 'cc-option-badge' },
                  scentAdj === 2 ? 'Special blend +$2' : 'Single note +$1',
                ),
              ),
              React.createElement('div', { className: 'cc-select-wrap' },
                React.createElement('select', {
                  className: 'cc-option-select',
                  value: scent,
                  onChange: e => setScent(e.target.value),
                  'aria-label': 'Choose scent',
                },
                  React.createElement('option', { value: 'Unscented' }, 'Unscented — no fragrance'),
                  React.createElement('optgroup', { label: '✦  Special Blends  (+$2.00)' },
                    SPECIAL_SCENTS.map(s =>
                      React.createElement('option', { key: s.name, value: s.name }, s.name)
                    ),
                  ),
                  React.createElement('optgroup', { label: '◦  Single Notes  (+$1.00)' },
                    SINGLE_SCENT_NAMES.map(n =>
                      React.createElement('option', { key: n, value: n }, n)
                    ),
                  ),
                ),
                React.createElement('span', { className: 'cc-select-chevron', 'aria-hidden': 'true' },
                  React.createElement('svg', { width: 10, height: 6, viewBox: '0 0 10 6', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' },
                    React.createElement('polyline', { points: '1,1 5,5 9,1' }),
                  ),
                ),
              ),
              scentNote && React.createElement('p', { className: 'cc-scent-hint' }, scentNote),
            ),

            /* Quantity */
            React.createElement('div', { className: 'cc-option-row' },
              React.createElement('p', { className: 'cc-option-label' }, 'Quantity'),
              React.createElement('div', { className: 'cc-qty-row' },
                React.createElement(QtyWheel, { qty, setQty, bulk, setBulk }),
                bulk && React.createElement('p', { className: 'cc-bulk-note' },
                  'For 50+ units we\'ll be in touch to arrange bulk pricing.',
                ),
              ),
            ),

            /* Personalise */
            product.personalizable &&
              React.createElement('div', { className: 'cc-option-row' },
                React.createElement('p', { className: 'cc-option-label' }, 'Personalization'),
                React.createElement('input', {
                  type: 'text',
                  className: 'cc-input cc-input-personal',
                  placeholder: 'Name, date, or short message…',
                  value: personalName,
                  onChange: e => setPersonalName(e.target.value),
                  maxLength: 30,
                }),
                React.createElement('p', { className: 'cc-char-count' }, personalName.length + '/30'),
              ),
          ),

          React.createElement('div', { className: 'cc-options-divider' }),

          /* ── Footer: total + CTA ── */
          React.createElement('div', { className: 'cc-overlay-footer' },
            React.createElement('div', { className: 'cc-total-row' },
              React.createElement('div', { className: 'cc-total-left' },
                React.createElement('span', { className: 'cc-total-label' },
                  bulk
                    ? 'Unit price (bulk)'
                    : qty === 1 ? 'Total' : 'Total (' + qty + ' items)',
                ),
                /* Savings line */
                !bulk && product.salePrice && (() => {
                  const saved = (product.price - product.salePrice + scentAdj * 0) * qty;
                  /* savings is on the base discount only, scentAdj applies to sale price */
                  const discount = (product.price - product.salePrice) * qty;
                  return discount > 0
                    ? React.createElement('span', { className: 'cc-savings-line' },
                        'You\'re saving $' + discount.toFixed(2) + '!',
                      )
                    : null;
                })(),
              ),
              React.createElement('span', { className: 'cc-total-amount' },
                bulk
                  ? '$' + unitPrice.toFixed(2) + ' / ea'
                  : '$' + totalPrice.toFixed(2),
              ),
            ),
            React.createElement('button', {
              className: 'cc-btn cc-btn-primary cc-btn-full' + (added ? ' cc-btn-added' : ''),
              onClick: addToCart,
            },
              added
                ? React.createElement(React.Fragment, null,
                    React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', style: { marginRight: '0.5rem' } },
                      React.createElement('polyline', { points: '20,6 9,17 4,12' }),
                    ),
                    'Added to Cart',
                  )
                : (bulk ? 'Request Bulk Order' : 'Add to Cart'),
            ),
          ),
        ),
      ),
    ),
  );
}

window.ProductOverlay = ProductOverlay;
