(function () {
  'use strict';

  if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
  window.scrollTo(0, 0);

  /* ---------------- Icons ---------------- */
  const ICONS = {
    phone: '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1C10.6 21 3 13.4 3 4c0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.2.2 2.4.6 3.6.1.3 0 .7-.2 1l-2.3 2.2z"/></svg>',
    whatsapp: '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M12 2a10 10 0 0 0-8.5 15.3L2 22l4.9-1.4A10 10 0 1 0 12 2zm5.4 14.1c-.2.7-1.3 1.3-1.9 1.4-.5.1-1.1.1-1.8-.1-.4-.1-.9-.3-1.6-.6-2.8-1.2-4.6-4-4.7-4.2-.1-.2-1.1-1.5-1.1-2.9s.7-2 1-2.3c.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.9 2.1c.1.2.1.4 0 .6l-.4.6-.6.6c-.2.2-.4.4-.2.8.2.4.9 1.5 2 2.4 1.4 1.2 2.5 1.6 2.9 1.7.3.2.5.1.7-.1l1-1.2c.2-.3.4-.2.7-.1l2.2 1c.3.2.5.3.6.4.1.2.1.7-.1 1.4z"/></svg>',
    mail: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="4" width="20" height="16" rx="3"/><path d="m2 7 10 6L22 7"/></svg>',
    facebook: '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M22 12a10 10 0 1 0-11.6 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.4v7A10 10 0 0 0 22 12z"/></svg>',
    instagram: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2.5" y="2.5" width="19" height="19" rx="5.5"/><circle cx="12" cy="12" r="4.2"/><circle cx="17.6" cy="6.4" r="1.2" fill="currentColor" stroke="none"/></svg>',
    cart: '<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 3h2l2.6 12.4a2 2 0 0 0 2 1.6h8.7a2 2 0 0 0 2-1.6L22 7H6"/><circle cx="9.5" cy="20.5" r="1.4" fill="currentColor" stroke="none"/><circle cx="18" cy="20.5" r="1.4" fill="currentColor" stroke="none"/></svg>',
    heart: '<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>',
    heartFill: '<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>',
    user: '<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="8" r="4"/><path d="M4 20c1.5-3.5 4.5-5 8-5s6.5 1.5 8 5"/></svg>',
    search: '<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="7"/><path d="m21 21-4-4"/></svg>',
    menu: '<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 7h16M4 12h16M4 17h16"/></svg>',
    close: '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"/></svg>',
    arrow: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>',
    map: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 21s-7-5.3-7-11a7 7 0 0 1 14 0c0 5.7-7 11-7 11z"/><circle cx="12" cy="10" r="2.6"/></svg>',
    shield: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"/><path d="m9 12 2 2 4-4"/></svg>',
    truck: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M2 6h12v10H2zM14 9h4l4 4v3h-8z"/><circle cx="6.5" cy="18.5" r="1.8"/><circle cx="17.5" cy="18.5" r="1.8"/></svg>',
    box: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="m12 3 9 4.5v9L12 21l-9-4.5v-9L12 3z"/><path d="m3 7.5 9 4.5 9-4.5M12 12v9"/></svg>',
    tag: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 11V4a1 1 0 0 1 1-1h7l10 10-8 8L3 11z"/><circle cx="8" cy="8" r="1.4" fill="currentColor" stroke="none"/></svg>',
    star: '<svg viewBox="0 0 24 24" width="17" height="17" fill="currentColor"><path d="m12 2 3 6.6 7 .8-5.2 4.9 1.4 7L12 17.8 5.8 21.3l1.4-7L2 9.4l7-.8L12 2z"/></svg>',
    check: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.4"><path d="m5 13 4 4L19 7"/></svg>',
    clock: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>',
    headset: '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 13a8 8 0 0 1 16 0"/><rect x="3" y="13" width="4" height="7" rx="2"/><rect x="17" y="13" width="4" height="7" rx="2"/><path d="M20 20a3 3 0 0 1-3 3h-4"/></svg>',
    bag: '<svg viewBox="0 0 24 24" width="44" height="44" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M5 8h14l-1.5 12a2 2 0 0 1-2 1.7h-7a2 2 0 0 1-2-1.7L5 8z"/><path d="M9 10V6a3 3 0 0 1 6 0v4"/></svg>',
    trash: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13a2 2 0 0 0 2 1.8h6A2 2 0 0 0 17 20l1-13M9 7V4h6v3"/></svg>',
    edit: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 20h4L20 8l-4-4L4 16v4z"/></svg>',
    logout: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M15 4h4a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-4"/><path d="m9 8-4 4 4 4M5 12h10"/></svg>',
    plus: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>',
    minus: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14"/></svg>',
    image: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="9" cy="9" r="2"/><path d="m21 15-4-4-9 9"/></svg>',
    gadgets: '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 13a8 8 0 0 1 16 0"/><rect x="2.5" y="13" width="3.5" height="6" rx="1.5"/><rect x="18" y="13" width="3.5" height="6" rx="1.5"/><path d="M20 19a3 3 0 0 1-3 3h-3"/></svg>',
    jewelry: '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M6 4h12l-2.5 4 2.5 4h-4l-2 8-2-8H6l2.5-4L6 4z"/></svg>',
    shoes: '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 16c3 0 4-1 6-1.5S14 13 20 12c1.5-.2 1.5-3.5 0-4-4.5-1.5-9 1-11 2.5S6.5 13 5 15"/><path d="M14 10.5 16 13M17.5 9l1.5 2"/></svg>',
    fragrances: '<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="8" y="9" width="8" height="11" rx="2.5"/><path d="M10 9V6a2 2 0 0 1 4 0v3M9 14h6"/></svg>',
  };
  document.querySelectorAll('.ic[data-ic]').forEach(function (el) {
    const k = el.getAttribute('data-ic');
    if (ICONS[k]) el.innerHTML = ICONS[k];
  });

  /* ---------------- Helpers ---------------- */
  const $ = (s, c) => (c || document).querySelector(s);
  const $$ = (s, c) => Array.from((c || document).querySelectorAll(s));

  function money(n) {
    return 'R ' + Number(n || 0).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  function toast(msg, type) {
    const wrap = $('#toastWrap');
    if (!wrap) return;
    const el = document.createElement('div');
    el.className = 'toast ' + (type || '');
    el.textContent = msg;
    wrap.appendChild(el);
    setTimeout(function () { el.classList.add('out'); setTimeout(function () { el.remove(); }, 320); }, 2600);
  }

  /* ---------------- Cart / Wishlist (localStorage) ---------------- */
  const LS_CART = 'tc_cart';
  const LS_WISH = 'tc_wish';

  function readLS(key) { try { return JSON.parse(localStorage.getItem(key)) || []; } catch { return []; } }
  function writeLS(key, val) { localStorage.setItem(key, JSON.stringify(val)); }

  function getCart() { return readLS(LS_CART); }
  function setCart(items) { writeLS(LS_CART, items); emitChange(); }
  function getWish() { return readLS(LS_WISH); }
  function setWish(items) { writeLS(LS_WISH, items); emitChange(); }

  function cartQty() { return getCart().reduce(function (s, i) { return s + i.qty; }, 0); }
  function wishQty() { return getWish().length; }

  function itemKey(it) { return it.slug + '|' + (it.size || ''); }
  function findItem(items, slug, size) { return items.find(function (i) { return i.slug === slug && (i.size || '') === (size || ''); }); }

  function updateBadges() {
    const cc = $('#cartCount');
    const wc = $('#wishCount');
    if (cc) { const n = cartQty(); cc.textContent = n; cc.hidden = n === 0; }
    if (wc) { const n = wishQty(); wc.textContent = n; wc.hidden = n === 0; }
  }

  /* ---------------- Catalog cache ---------------- */
  let catalogPromise = null;
  function getCatalog() {
    if (!catalogPromise) {
      catalogPromise = fetch('/api/products').then(function (r) { return r.json(); }).catch(function () { return []; });
    }
    return catalogPromise;
  }

  function findBySlug(slug, list) { return list.find(function (p) { return p.slug === slug; }); }

  /* ---------------- Drawer ---------------- */
  const drawer = $('#cartDrawer');
  const overlay = $('#drawerOverlay');

  function openDrawer() { if (drawer) { drawer.classList.add('open'); if (overlay) overlay.classList.add('open'); renderDrawer(); } }
  function closeDrawer() { if (drawer) drawer.classList.remove('open'); if (overlay) overlay.classList.remove('open'); }
  function toggleDrawer() { if (drawer && drawer.classList.contains('open')) closeDrawer(); else openDrawer(); }

  async function renderDrawer() {
    if (!drawer) return;
    const body = $('#drawerBody');
    const foot = $('#drawerFoot');
    const items = getCart();
    if (!items.length) {
      if (body) body.innerHTML = '<div class="empty" style="padding:40px 10px;"><div class="ico" data-ic="bag"></div><h3>Your cart is empty</h3><p>Add something fresh to get the drip going.</p><a class="btn btn-gold" href="/gadgets">Shop now</a></div>';
      if (foot) foot.hidden = true;
      renderIcons(body);
      updateBadges();
      return;
    }
    const cat = await getCatalog();
    let html = '';
    let total = 0;
    for (const it of items) {
      const p = findBySlug(it.slug, cat) || { name: 'Item', price: null, image: '', stock: 0 };
      const price = p.price != null ? p.price : 0;
      total += price * it.qty;
      html += `<div class="drawer-item">
        <a href="/product/${it.slug}"><img src="/public/images/products/${p.image || 'placeholder'}.jpeg" alt="" onerror="this.style.opacity=0.15"></a>
        <div style="flex:1;">
          <a class="di-name" href="/product/${it.slug}">${(p.name || '').replace(/"/g, '&quot;')}${it.size ? ' <span class="di-size">' + it.size + '</span>' : ''}</a>
          <div class="di-meta">${p.price != null ? money(p.price) : 'Price on request'}</div>
          <div class="drawer-qty">
            <button data-action="qty" data-key="${itemKey(it)}" data-delta="-1" aria-label="Decrease">−</button>
            <span>${it.qty}</span>
            <button data-action="qty" data-key="${itemKey(it)}" data-delta="1" aria-label="Increase">+</button>
          </div>
        </div>
        <div style="text-align:right;">
          <div class="di-price">${money(price * it.qty)}</div>
          <button class="cl-remove" data-action="remove" data-key="${itemKey(it)}" style="color:var(--muted);font-size:12px;margin-top:8px;">Remove</button>
        </div>
      </div>`;
    }
    if (body) body.innerHTML = html;
    if (foot) { foot.hidden = false; const t = $('#drawerTotal'); if (t) t.textContent = money(total); }
    renderIcons(body);
    updateBadges();
  }

  function renderIcons(scope) { $$('.ic[data-ic]', scope).forEach(function (el) { const k = el.getAttribute('data-ic'); if (ICONS[k]) el.innerHTML = ICONS[k]; }); }

  function emitChange() { updateBadges(); renderDrawer(); }

  /* ---------------- Actions ---------------- */
  function addToCart(slug, qty, size) {
    getCatalog().then(function () {
      const items = getCart();
      const found = findItem(items, slug, size);
      if (found) found.qty = Math.min(99, found.qty + (qty || 1));
      else {
        const it = { slug: slug, qty: qty || 1 };
        if (size) it.size = size;
        items.push(it);
      }
      setCart(items);
      toast('Added to cart');
      openDrawer();
    });
  }

  function toggleWish(slug, btn) {
    const items = getWish();
    const idx = items.indexOf(slug);
    let active = false;
    if (idx >= 0) { items.splice(idx, 1); toast('Removed from wishlist'); }
    else { items.push(slug); active = true; toast('Added to wishlist'); }
    setWish(items);
    if (btn) { btn.classList.toggle('active', active); btn.querySelector('.ic').innerHTML = ICONS[active ? 'heartFill' : 'heart']; }
    updateBadges();
  }

  document.addEventListener('click', function (e) {
    const addBtn = e.target.closest('.add-to-cart');
    if (addBtn) { e.preventDefault(); addToCart(addBtn.dataset.id || addBtn.dataset.slug, 1); return; }

    const wishBtn = e.target.closest('.wish-btn');
    if (wishBtn) { e.preventDefault(); toggleWish(wishBtn.dataset.slug, wishBtn); return; }

    const qb = e.target.closest('[data-action="qty"]');
    if (qb) {
      const items = getCart();
      const it = items.find(function (i) { return itemKey(i) === qb.dataset.key; });
      if (it) {
        it.qty = Math.min(99, Math.max(1, it.qty + Number(qb.dataset.delta)));
        setCart(items);
      }
      return;
    }
    const rm = e.target.closest('[data-action="remove"]');
    if (rm) {
      setCart(getCart().filter(function (i) { return itemKey(i) !== rm.dataset.key; }));
      toast('Removed from cart');
      return;
    }
  });

  /* ---------------- UI wiring ---------------- */
  $('#cartBtn') && $('#cartBtn').addEventListener('click', function (e) { e.preventDefault(); toggleDrawer(); });
  $('#drawerClose') && $('#drawerClose').addEventListener('click', closeDrawer);
  overlay && overlay.addEventListener('click', closeDrawer);

  /* ---------------- Quickbar ---------------- */
  var qb = $('#quickbar');
  var qbBtn = $('#quickbarBtn');
  if (qb && qbBtn) {
    qbBtn.addEventListener('click', function (e) {
      e.stopPropagation();
      qb.classList.toggle('open');
    });
    document.addEventListener('click', function (e) {
      if (!qb.contains(e.target)) qb.classList.remove('open');
    });
  }

  const menuBtn = $('#menuBtn');
  const body = document.body;
  if (menuBtn) {
    const panel = document.createElement('div');
    panel.className = 'mobile-nav';
    panel.innerHTML = `<div class="mobile-nav-panel">
      <button class="mobile-nav-close" id="mobileNavClose" aria-label="Close menu"><i class="ic" data-ic="close"></i></button>
      <a href="/">Home</a>
      <a href="/all">All</a>
      <a href="/gadgets">Gadgets</a>
      <a href="/jewelry">Jewelry</a>
      <a href="/shoes">Shoes</a>
      <a href="/fragrances">Fragrances</a>
      <a href="/about">About Us</a>
      <a href="/contact">Contact</a>
      <a href="/testimonials">Testimonials</a>
      <a href="/cart">Cart</a>
      <a href="/account">Account</a>
    </div>`;
    body.appendChild(panel);
    renderIcons(panel);
    menuBtn.addEventListener('click', function () { panel.classList.add('open'); });
    panel.addEventListener('click', function (e) { if (e.target === panel || e.target.closest('#mobileNavClose')) panel.classList.remove('open'); });
  }

  /* ---------------- Product card hover slideshow ---------------- */
  $$('.product-card[data-gallery]').forEach(function (card) {
    let images;
    try { images = JSON.parse(card.getAttribute('data-gallery')); } catch (e) { return; }
    if (!images || images.length < 2) return;

    const media = card.querySelector('.product-media');
    const slides = [];
    let current = 0;
    let interval = null;

    /* create slide images */
    images.forEach(function (img, i) {
      if (i === 0) return;
      const el = document.createElement('img');
      el.className = 'slide-img';
      el.src = img.src;
      el.alt = img.alt || '';
      el.loading = 'lazy';
      media.appendChild(el);
      slides.push(el);
    });

    /* create dot indicators */
    const dotsWrap = document.createElement('div');
    dotsWrap.className = 'product-dots';
    var dots = [];
    slides.forEach(function () {
      var d = document.createElement('span');
      d.className = 'product-dot';
      dotsWrap.appendChild(d);
      dots.push(d);
    });
    media.appendChild(dotsWrap);

    function showSlide(index) {
      slides.forEach(function (s, i) { s.classList.toggle('active', i === index); });
      dots.forEach(function (d, i) { d.classList.toggle('active', i === index); });
    }

    function nextSlide() {
      current = (current + 1) % slides.length;
      showSlide(current);
    }

    function startSlideshow() {
      if (slides.length === 0) return;
      current = 0;
      showSlide(0);
      interval = setInterval(nextSlide, 1400);
    }

    function stopSlideshow() {
      clearInterval(interval);
      interval = null;
      current = 0;
      slides.forEach(function (s) { s.classList.remove('active'); });
      dots.forEach(function (d) { d.classList.remove('active'); });
    }

    card.addEventListener('mouseenter', startSlideshow);
    card.addEventListener('mouseleave', stopSlideshow);
  });

  /* ---------------- Reveal on scroll ---------------- */
  if ('IntersectionObserver' in window) {
    const io = new IntersectionObserver(function (entries) {
      entries.forEach(function (en) { if (en.isIntersecting) { en.target.classList.add('visible'); io.unobserve(en.target); } });
    }, { threshold: 0.12 });
    $$('.reveal').forEach(function (el) { io.observe(el); });
  } else {
    $$('.reveal').forEach(function (el) { el.classList.add('visible'); });
  }

  /* ---------------- Preloader ---------------- */
  function hidePreloader() {
    const p = document.getElementById('preloader');
    if (p) p.classList.add('hidden');
  }
  if (document.readyState === 'complete') { setTimeout(hidePreloader, 700); }
  else {
    window.addEventListener('load', function () { setTimeout(hidePreloader, 700); });
    setTimeout(hidePreloader, 3500);
  }

  /* ---------------- Page transitions ---------------- */
  const navFlag = sessionStorage.getItem('tc_tnav');
  if (navFlag) {
    sessionStorage.removeItem('tc_tnav');
    const ptIn = document.getElementById('pageTransition');
    if (ptIn) {
      ptIn.classList.add('show');
      requestAnimationFrame(function () {
        requestAnimationFrame(function () { ptIn.classList.remove('show'); });
      });
    }
  }

  document.addEventListener('click', function (e) {
    const a = e.target.closest('a[href]');
    if (!a) return;
    const href = a.getAttribute('href') || '';
    if (a.target && a.target !== '_self') return;
    if (/^(https?:|mailto:|tel:|javascript:|#)/.test(href) || href.startsWith('//')) return;
    if (!href.startsWith('/')) return;
    if (href.startsWith('/admin') || href.startsWith('/account/logout')) return;
    e.preventDefault();
    const pt = document.getElementById('pageTransition');
    if (pt && !pt.classList.contains('show')) pt.classList.add('show');
    sessionStorage.setItem('tc_tnav', '1');
    setTimeout(function () { window.location.href = href; }, 340);
  });

  window.TC = { addToCart, toggleWish, getCart, getWish, getCatalog, toast, money, updateBadges };

  updateBadges();
  renderDrawer();
})();
