(function () {
  'use strict';
  const $ = (s) => document.querySelector(s);
  const container = $('#cartPageItems');
  const summary = $('#cartSummary');
  let coupon = null;
  let lastTotal = 0;

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

  function itemKey(it) { return it.slug + '|' + (it.size || ''); }

  async function render() {
    const items = TC.getCart();
    if (!items.length) {
      container.innerHTML = '<div class="empty" style="padding:60px 20px;"><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">Start shopping</a></div>';
      summary.hidden = true;
      return;
    }
    const cat = await TC.getCatalog();
    let html = '';
    let subtotal = 0;
    for (const it of items) {
      const p = cat.find((x) => x.slug === it.slug) || { name: 'Item', price: null, image: '' };
      const price = p.price != null ? p.price : 0;
      subtotal += price * it.qty;
      const img = p.image ? `/public/images/products/${p.image}` : '';
      html += `<div class="cart-line">
        <a href="/product/${it.slug}"><img src="${img}" alt="${(p.name || '').replace(/"/g, '&quot;')}" onerror="this.style.opacity=0.15"></a>
        <div class="cl-info">
          <a href="/product/${it.slug}">${p.name || 'Item'}${it.size ? ' <span class="di-size">' + it.size + '</span>' : ''}</a>
          <div class="cl-meta">${p.price != null ? money(p.price) : 'Price on request'}</div>
          <div class="cl-meta" style="display:flex; align-items:center; gap:10px; margin-top:8px;">
            <button class="btn btn-dark btn-sm" data-act="qty" data-key="${itemKey(it)}" data-d="-1" style="padding:4px 10px;">−</button>
            <b>${it.qty}</b>
            <button class="btn btn-dark btn-sm" data-act="qty" data-key="${itemKey(it)}" data-d="1" style="padding:4px 10px;">+</button>
          </div>
        </div>
        <div class="cl-right">
          <div class="cl-price">${money(price * it.qty)}</div>
          <button class="cl-remove" data-act="remove" data-key="${itemKey(it)}">Remove</button>
        </div>
      </div>`;
    }
    container.innerHTML = html;
    summary.hidden = false;
    $('#sumSubtotal').textContent = money(subtotal);

    const discount = coupon ? coupon.discount : 0;
    const after = subtotal - discount;
    const freeThresh = (window.TC_SITE && Number(window.TC_SITE.free_shipping_threshold)) || 0;
    const fee = after >= freeThresh ? 0 : (window.TC_SITE && Number(window.TC_SITE.shipping_fee)) || 0;
    const total = Math.max(0, after + fee);
    lastTotal = total;
    $('#sumShipping').textContent = fee === 0 ? 'FREE' : money(fee);
    $('#sumTotal').textContent = money(total);

    if (coupon) {
      $('#couponResult').innerHTML = `<div class="coupon-applied"><span>${coupon.code} (−${money(coupon.discount)})</span><button id="removeCoupon" style="color:var(--red); font-size:12px; font-weight:800;">✕</button></div>`;
      const rc = $('#removeCoupon');
      if (rc) rc.addEventListener('click', function () { coupon = null; render(); });
    } else {
      $('#couponResult').innerHTML = '';
    }
  }

  async function applyCoupon() {
    const code = $('#couponInput').value.trim();
    if (!code) return TC.toast('Enter a discount code', 'error');
    const items = TC.getCart();
    const cat = await TC.getCatalog();
    let subtotal = 0;
    for (const it of items) {
      const p = cat.find((x) => x.slug === it.slug);
      if (p && p.price != null) subtotal += p.price * it.qty;
    }
    const res = await fetch('/api/coupons/validate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code, subtotal }),
    }).then((r) => r.json());
    if (res.valid) {
      coupon = res;
      TC.toast('Discount applied');
    } else {
      TC.toast(res.error || 'Invalid code', 'error');
    }
    render();
  }

  document.addEventListener('click', function (e) {
    const q = e.target.closest('[data-act="qty"]');
    if (q) {
      const items = TC.getCart();
      const it = items.find((x) => itemKey(x) === q.dataset.key);
      if (it) {
        it.qty = Math.min(99, Math.max(1, it.qty + Number(q.dataset.d)));
        localStorage.setItem('tc_cart', JSON.stringify(items));
        TC.updateBadges();
        render();
      }
      return;
    }
    const rm = e.target.closest('[data-act="remove"]');
    if (rm) {
      localStorage.setItem('tc_cart', JSON.stringify(TC.getCart().filter((x) => itemKey(x) !== rm.dataset.key)));
      TC.updateBadges();
      render();
      return;
    }
    if (e.target.closest('#applyCouponBtn')) applyCoupon();
  });

  window.addEventListener('storage', render);
  render();
})();
