(function () {
  'use strict';
  const container = document.getElementById('wishlistItems');
  function money(n) {
    return 'R ' + Number(n || 0).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }
  async function render() {
    const ids = TC.getWish();
    if (!ids.length) {
      container.innerHTML = '<div class="empty" style="padding:60px 20px;"><div class="ico" data-ic="heart"></div><h3>Nothing saved yet</h3><p>Tap the heart on any product to save it here for later.</p><a class="btn btn-gold" href="/">Explore products</a></div>';
      return;
    }
    const cat = await TC.getCatalog();
    const products = ids
      .map((slug) => cat.find((p) => p.slug === slug))
      .filter(Boolean);
    if (!products.length) {
      container.innerHTML = '<div class="empty"><h3>No saved products</h3><a class="btn btn-gold" href="/">Explore products</a></div>';
      return;
    }
    let html = '<div class="product-grid">';
    for (const p of products) {
      const noPrice = p.price == null || p.price <= 0;
      html += `<article class="product-card">
        <div class="product-media">
          <a href="/product/${p.slug}"><img src="/public/images/products/${p.image}" alt="${(p.name || '').replace(/"/g, '&quot;')}" loading="lazy"></a>
          <button class="wish-btn active" data-remove="${p.slug}" aria-label="Remove from wishlist"><i class="ic" data-ic="heart"></i></button>
        </div>
        <div class="product-body">
          <div class="product-cat">${p.category_name || 'New Drop'}</div>
          <h3 class="product-name"><a href="/product/${p.slug}">${p.name}</a></h3>
          <div class="product-price">${noPrice ? '<span class="price-request">Price on request</span>' : `<span class="price">${money(p.price)}</span>`}</div>
          <div class="product-cta">
            ${noPrice
              ? ''
              : `<button class="btn btn-gold btn-sm add-to-cart" data-slug="${p.slug}"><i class="ic" data-ic="cart"></i> Add</button>`}
            <a class="btn btn-dark btn-sm" href="/product/${p.slug}">View</a>
          </div>
        </div>
      </article>`;
    }
    html += '</div>';
    container.innerHTML = html;
    container.querySelectorAll('.ic[data-ic]').forEach(function (el) { el.innerHTML = el.getAttribute('data-ic') === 'heart' ? '<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>' : ''; });
    container.querySelectorAll('[data-remove]').forEach(function (b) {
      b.addEventListener('click', function () {
        TC.toggleWish(b.dataset.remove);
        render();
      });
    });
  }
  document.addEventListener('click', function (e) {
    const add = e.target.closest('.add-to-cart');
    if (add) { e.preventDefault(); TC.addToCart(add.dataset.slug, 1); }
  });
  render();
})();
