(function () {
  'use strict';
  const $ = (s) => document.querySelector(s);
  let coupon = null;
  let subtotal = 0;

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

  function totals() {
    const discount = coupon ? coupon.discount : 0;
    const after = subtotal - discount;
    const freeThresh = Number(window.TC_SITE.free_shipping_threshold) || 0;
    const fee = after >= freeThresh ? 0 : Number(window.TC_SITE.shipping_fee) || 0;
    $('#coSubtotal').textContent = money(subtotal);
    $('#coShipping').textContent = fee === 0 ? 'FREE' : money(fee);
    $('#coTotal').textContent = money(Math.max(0, after + fee));
    return { discount, fee, total: Math.max(0, after + fee) };
  }

  async function renderItems() {
    const items = TC.getCart();
    const cat = await TC.getCatalog();
    let html = '';
    subtotal = 0;
    for (const it of items) {
      const p = cat.find((x) => x.slug === it.slug);
      if (!p || p.price == null) {
        TC.toast('Some items need pricing — remove them and continue.', 'error');
        continue;
      }
      subtotal += p.price * it.qty;
      html += `<div class="drawer-item" style="padding:10px 0;">
        <img src="/public/images/products/${p.image}" alt="">
        <div style="flex:1;"><div class="di-name">${p.name}${it.size ? ' <span class="di-size">' + it.size + '</span>' : ''}</div><div class="di-meta">Qty ${it.qty} × ${money(p.price)}</div></div>
        <div class="di-price">${money(p.price * it.qty)}</div>
      </div>`;
    }
    $('#coItems').innerHTML = html;
    totals();
  }

  async function applyCoupon() {
    const code = $('#coCoupon').value.trim();
    if (!code) return TC.toast('Enter a discount code', 'error');
    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;
      $('#coCouponResult').innerHTML = `<div class="coupon-applied"><span>${res.code} (−${money(res.discount)})</span><button id="coRemoveCoupon" style="color:var(--red);font-weight:800;">✕</button></div>`;
      TC.toast('Discount applied');
    } else {
      $('#coCouponResult').innerHTML = `<div class="form-error">${res.error || 'Invalid code'}</div>`;
    }
    totals();
  }

  document.addEventListener('click', function (e) {
    if (e.target.closest('#coApplyCoupon')) applyCoupon();
    if (e.target.closest('#coRemoveCoupon')) { coupon = null; $('#coCouponResult').innerHTML = ''; totals(); }
    const opt = e.target.closest('.pay-option');
    if (opt) { document.querySelectorAll('.pay-option').forEach((x) => x.classList.remove('selected')); opt.classList.add('selected'); opt.querySelector('input').checked = true; }
  });

  document.querySelectorAll('.pay-option input').forEach(function (r) {
    r.addEventListener('change', function () {
      document.querySelectorAll('.pay-option').forEach((x) => x.classList.toggle('selected', x.querySelector('input').checked));
    });
  });

  $('#checkoutForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    const btn = $('#placeOrderBtn');
    const items = TC.getCart().map((i) => ({ id: null, slug: i.slug, qty: i.qty, size: i.size || '' }));
    if (!items.length) return TC.toast('Your cart is empty', 'error');

    const cat = await TC.getCatalog();
    const payload = {
      items: items.map((i) => ({ id: (cat.find((p) => p.slug === i.slug) || {}).id, qty: i.qty, size: i.size })),
      customer: { name: $('#coName').value, email: $('#coEmail').value, phone: $('#coPhone').value },
      shipping: {
        line1: $('#coLine1').value, line2: $('#coLine2').value, city: $('#coCity').value,
        province: $('#coProvince').value, postal: $('#coPostal').value, country: $('#coCountry').value,
      },
      couponCode: coupon ? coupon.code : '',
      paymentMethod: document.querySelector('input[name="payment"]:checked').value,
      notes: $('#coNotes').value,
    };

    btn.disabled = true;
    btn.innerHTML = 'Processing...';
    try {
      const res = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        TC.toast(data.error || 'Could not place order', 'error');
        btn.disabled = false;
        btn.innerHTML = '<i class="ic" data-ic="shield"></i> Place order';
        return;
      }
      localStorage.setItem('tc_cart', JSON.stringify([]));
      TC.updateBadges();

      if (data.payment_method === 'cod') {
        window.location.href = '/order/' + data.order_number;
        return;
      }
      if (data.payment && data.payment.action) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = data.payment.action;
        form.style.display = 'none';
        Object.keys(data.payment.pf).forEach((k) => {
          const input = document.createElement('input');
          input.type = 'hidden';
          input.name = k;
          input.value = data.payment.pf[k];
          form.appendChild(input);
        });
        document.body.appendChild(form);
        form.submit();
      } else {
        window.location.href = '/order/' + data.order_number;
      }
    } catch (err) {
      TC.toast('Network error — please try again', 'error');
      btn.disabled = false;
      btn.innerHTML = '<i class="ic" data-ic="shield"></i> Place order';
    }
  });

  renderItems();
})();
