(function () {
  'use strict';
  const slug = window.PRODUCT_SLUG;
  if (!slug) return;

  /* qty */
  let qty = 1;
  const val = document.getElementById('qtyVal');
  const minus = document.getElementById('qtyMinus');
  const plus = document.getElementById('qtyPlus');
  if (minus) minus.addEventListener('click', function () { qty = Math.max(1, qty - 1); val.textContent = qty; });
  if (plus) plus.addEventListener('click', function () { qty = Math.min(99, qty + 1); val.textContent = qty; });

  /* size picker */
  let size = '';
  const sizeGrid = document.getElementById('sizeGrid');
  if (sizeGrid) {
    sizeGrid.addEventListener('click', function (e) {
      const chip = e.target.closest('.pd-size');
      if (!chip) return;
      sizeGrid.querySelectorAll('.pd-size').forEach(function (x) { x.classList.remove('active'); });
      chip.classList.add('active');
      size = chip.dataset.size;
      const err = document.getElementById('sizeErr');
      if (err) err.hidden = true;
    });
  }
  function requireSize() {
    const hasSizes = document.querySelectorAll('.pd-size').length > 0;
    const err = document.getElementById('sizeErr');
    if (hasSizes && !size) {
      if (err) err.hidden = false;
      TC.toast('Select a size first', 'error');
      return false;
    }
    return true;
  }

  /* size guide toggle */
  const guideBtn = document.getElementById('sizeGuideBtn');
  const guide = document.getElementById('sizeGuide');
  if (guideBtn && guide) {
    guideBtn.addEventListener('click', function () {
      const open = !guide.hidden;
      guide.hidden = open;
      guideBtn.classList.toggle('open', !open);
    });
  }

  /* add to cart */
  const addBtn = document.getElementById('addCartBtn');
  if (addBtn) addBtn.addEventListener('click', function () {
    if (!requireSize()) return;
    TC.addToCart(slug, qty, size);
  });

  /* buy now: add then go to checkout */
  const buyBtn = document.getElementById('buyNowBtn');
  if (buyBtn) buyBtn.addEventListener('click', function () {
    if (!requireSize()) return;
    const items = TC.getCart();
    const found = items.find(function (i) { return i.slug === slug && (i.size || '') === size; });
    if (found) found.qty = Math.min(99, found.qty + qty);
    else items.push({ slug: slug, qty: qty, size: size || undefined });
    localStorage.setItem('tc_cart', JSON.stringify(items));
    TC.updateBadges();
    window.location.href = '/checkout';
  });

  /* wishlist */
  const wishBtn = document.getElementById('wishBtn');
  const wishLabel = document.getElementById('wishLabel');
  function paint() {
    const active = TC.getWish().includes(slug);
    if (wishBtn) {
      wishBtn.classList.toggle('active', active);
      const ic = wishBtn.querySelector('.ic');
      if (ic) ic.innerHTML = active
        ? '<svg viewBox="0 0 24 24" width="19" height="19" fill="currentColor"><path d="M12 21C7 16.5 2.5 12.8 2.5 8.7 2.5 5.7 4.8 3.5 7.5 3.5c1.8 0 3.4.9 4.5 2.4 1.1-1.5 2.7-2.4 4.5-2.4 2.7 0 5 2.2 5 5.2 0 4.1-4.5 7.8-9.5 12.3z"/></svg>'
        : '<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 21C7 16.5 2.5 12.8 2.5 8.7 2.5 5.7 4.8 3.5 7.5 3.5c1.8 0 3.4.9 4.5 2.4 1.1-1.5 2.7-2.4 4.5-2.4 2.7 0 5 2.2 5 5.2 0 4.1-4.5 7.8-9.5 12.3z"/></svg>';
      if (wishLabel) wishLabel.textContent = active ? 'Saved to wishlist' : 'Add to wishlist';
    }
  }
  if (wishBtn) wishBtn.addEventListener('click', function () { TC.toggleWish(slug); setTimeout(paint, 50); });
  paint();

  /* gallery thumbs */
  document.querySelectorAll('.pd-thumb').forEach(function (t) {
    t.addEventListener('click', function () {
      document.querySelectorAll('.pd-thumb').forEach(function (x) { x.classList.remove('active'); });
      t.classList.add('active');
      document.getElementById('mainImg').src = t.dataset.src;
    });
  });

  /* product review form */
  const prForm = document.getElementById('productReviewForm');
  if (prForm) {
    let rating = 5;
    const picker = document.getElementById('prPicker');
    if (picker) {
      picker.querySelectorAll('.sp-star').forEach(function (b) {
        b.addEventListener('click', function () {
          rating = Number(b.dataset.v);
          picker.querySelectorAll('.sp-star').forEach(function (x) { x.classList.toggle('on', Number(x.dataset.v) <= rating); });
        });
      });
      picker.querySelectorAll('.sp-star')[4].classList.add('on');
    }
    prForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const btn = prForm.querySelector('button[type="submit"]');
      btn.disabled = true;
      fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: document.getElementById('prName').value,
          title: document.getElementById('prTitle').value,
          body: document.getElementById('prBody').value,
          rating: rating,
          product_id: window.PRODUCT_ID,
        }),
      })
        .then(function (r) { return r.json(); })
        .then(function (d) {
          if (d.ok) { TC.toast('Thanks! Review submitted for approval.'); prForm.reset(); }
          else TC.toast(d.error || 'Could not submit', 'error');
        })
        .catch(function () { TC.toast('Network error', 'error'); })
        .finally(function () { btn.disabled = false; btn.textContent = 'Submit review'; });
    });
  }
})();
