/* MAPS - same add-to-cart feedback everywhere (11/20/2026, persona review fix #10).
   Related supplies on product pages and the Shop pages add items with their own
   fetch('/cart/addcart') call, so the buyer got no confirmation box, the header cart
   count stayed stale until reload, and GA4 never saw the add_to_cart.
   For every successful add made that way, this:
     - updates the header cart count the same way the theme does (updateminicart),
     - fires the theme's own "cart-add-success" event (GA4 add_to_cart via the site's tracking),
     - shows the same "Added to your cart / Checkout now / View cart" box as the regular button.
   The theme's own Add to cart buttons use jQuery ajax, not fetch, so they are untouched. */
(function () {
  if (window.__mxCartAdd) return; window.__mxCartAdd = 1;
  if (!window.fetch) return;
  var orig = window.fetch;

  function toast() {
    var old = document.querySelector('.mx-cart-toast'); if (old) old.remove();
    var d = document.createElement('div'); d.className = 'mx-cart-toast'; d.setAttribute('role', 'status');
    d.innerHTML = '<button type="button" aria-label="Close">&times;</button><b>Added to your cart</b>' +
      '<div class="mx-row"><a class="mx-go" href="/checkout">Checkout now</a><a class="mx-view" href="/cart">View cart</a></div>';
    d.querySelector('button').onclick = function () { d.remove(); };
    document.body.appendChild(d);
    setTimeout(function () { if (d.parentNode) d.remove(); }, 10000);
  }

  function afterAdd(j) {
    if (!j || j.result !== 'success') return;
    try {
      if (typeof window.updateminicart === 'function') window.updateminicart(j, false, 'add-item');
      else if (j.minicart_totals && j.minicart_totals.cart_item_count != null)
        document.querySelectorAll('.minicart_count').forEach(function (e) { e.textContent = j.minicart_totals.cart_item_count; });
    } catch (e) {}
    try {
      var it = Array.isArray(j.minicart_items) ? j.minicart_items[0] : j.minicart_items;
      if (it && typeof window.eventCleanProductData === 'function' && typeof window.createNewEvent === 'function') {
        var d = window.eventCleanProductData(it); d.view = 'Products List';
        document.dispatchEvent(window.createNewEvent('cart-add-success', { detail: d }));
      }
    } catch (e) {}
    try { toast(); } catch (e) {}
  }

  window.fetch = function (input, init) {
    var p = orig.apply(this, arguments);
    try {
      var url = typeof input === 'string' ? input : (input && input.url) || '';
      var method = (init && init.method) || (input && input.method) || 'GET';
      if (/\/cart\/addcart\b/.test(url) && /post/i.test(method)) {
        p.then(function (r) { return r.clone().json(); }).then(afterAdd).catch(function () {});
      }
    } catch (e) {}
    return p;
  };
})();
