/** Shopify CDN: Minification failed

Line 21:0 Unexpected "("
Line 28:2 Comments in CSS use "/* ... */" instead of "//"
Line 74:2 Comments in CSS use "/* ... */" instead of "//"
Line 120:2 Comments in CSS use "/* ... */" instead of "//"
Line 133:2 Comments in CSS use "/* ... */" instead of "//"
Line 135:2 Comments in CSS use "/* ... */" instead of "//"
Line 137:4 Comments in CSS use "/* ... */" instead of "//"

**/
/* ============================================================================
   Theme-Pfad: assets/lw-cart-page.js
   V6 "Cool Apple Day-One" · LW24 Cart-Page Mutations + Re-Render
   ----------------------------------------------------------------------------
   Bindet die Quantity-Stepper und Remove-Buttons an die Shopify Cart-API.
   Re-rendert die Section nach jeder Änderung über die Section-Rendering-API.
   Feuert "cart:updated" damit der Header-Counter + Drawer mitkommen.
   ============================================================================ */

(function () {
  if (window.__lwCartPageInit) return;
  window.__lwCartPageInit = true;

  const SECTION_MAIN = 'main-cart-items';
  const SECTION_FOOT = 'main-cart-footer';

  // ---------- Helpers ----------
  function debounce(fn, ms) {
    let t;
    return function () {
      clearTimeout(t);
      const args = arguments, ctx = this;
      t = setTimeout(() => fn.apply(ctx, args), ms);
    };
  }

  async function fetchCart() {
    const res = await fetch('/cart.js', { headers: { Accept: 'application/json' } });
    return res.json();
  }

  async function updateLine(line, qty) {
    const res = await fetch('/cart/change.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
      body: JSON.stringify({ id: line, quantity: qty, sections: [SECTION_MAIN, SECTION_FOOT] })
    });
    return res.json();
  }

  function replaceSectionHTML(sectionId, html) {
    if (!html) return;
    const wrapper = document.querySelector('#shopify-section-' + sectionId);
    if (!wrapper) return;
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const fresh = doc.querySelector('#shopify-section-' + sectionId);
    if (fresh) wrapper.innerHTML = fresh.innerHTML;
    else wrapper.innerHTML = html;
  }

  function dispatchCartUpdated(cart) {
    document.dispatchEvent(new CustomEvent('cart:updated', { detail: cart }));
  }

  function showSpinner(target, on) {
    if (!target) return;
    target.classList.toggle('is-loading', !!on);
    target.style.pointerEvents = on ? 'none' : '';
    target.style.opacity = on ? '0.5' : '';
  }

  // ---------- Handlers ----------
  async function handleStep(btn) {
    const item = btn.closest('[data-cart-line-item]');
    if (!item) return;
    const lineKey = btn.getAttribute('data-line-key');
    const step = parseInt(btn.getAttribute('data-cart-qty-step'), 10);
    const input = item.querySelector('[data-cart-qty-input]');
    if (!input) return;
    const current = parseInt(input.value, 10) || 0;
    const next = Math.max(0, current + step);
    await applyQuantity(item, lineKey, next);
  }

  async function handleRemove(btn) {
    const item = btn.closest('[data-cart-line-item]');
    if (!item) return;
    const lineKey = btn.getAttribute('data-line-key');
    await applyQuantity(item, lineKey, 0);
  }

  async function handleInputChange(input) {
    const item = input.closest('[data-cart-line-item]');
    if (!item) return;
    const lineKey = input.getAttribute('data-line-key');
    const next = Math.max(0, parseInt(input.value, 10) || 0);
    await applyQuantity(item, lineKey, next);
  }

  async function applyQuantity(item, lineKey, qty) {
    showSpinner(item, true);
    try {
      const data = await updateLine(lineKey, qty);
      if (data && data.sections) {
        replaceSectionHTML(SECTION_MAIN, data.sections[SECTION_MAIN]);
        replaceSectionHTML(SECTION_FOOT, data.sections[SECTION_FOOT]);
      }
      const cart = await fetchCart();
      dispatchCartUpdated(cart);
    } catch (err) {
      console.error('[lw-cart-page] update failed', err);
      showSpinner(item, false);
    }
  }

  const debouncedInput = debounce(handleInputChange, 400);

  // ---------- Delegation ----------
  document.addEventListener('click', function (e) {
    const stepBtn = e.target.closest('[data-cart-qty-step]');
    if (stepBtn) { e.preventDefault(); handleStep(stepBtn); return; }
    const rmBtn = e.target.closest('[data-cart-remove]');
    if (rmBtn) { e.preventDefault(); handleRemove(rmBtn); return; }
  });

  document.addEventListener('change', function (e) {
    const input = e.target.closest('[data-cart-qty-input]');
    if (input) debouncedInput(input);
  });

  // Note: textarea[name="note"] wird beim Submit mitgesendet — kein Extra-JS nötig.

  // ---------- Listener für externe Updates (Quick-Add, Drawer) ----------
  document.addEventListener('cart:updated', async function (e) {
    // Re-render only if not triggered by us (avoid loop)
    if (e.detail && e.detail.__fromCartPage) return;
    if (!document.body.classList.contains('template-cart')) return;
    try {
      const res = await fetch(window.location.pathname + '?section_id=' + SECTION_MAIN);
      if (res.ok) {
        const html = await res.text();
        replaceSectionHTML(SECTION_MAIN, html);
      }
      const res2 = await fetch(window.location.pathname + '?section_id=' + SECTION_FOOT);
      if (res2.ok) {
        const html2 = await res2.text();
        replaceSectionHTML(SECTION_FOOT, html2);
      }
    } catch (err) { /* silent */ }
  });
})();