/* Exefai fix 2026-11-03: "Store Identifier not found" on first cart load.
   1) Adds the Store-Identifier header to any Salla API call that lacks it.
   2) Removes the stray ?scope= parameter from cart links and the cart URL.
   3) Hides that one toast if it still slips through.
   Remove once Salla deletes the orphan market/scope 1333898933. */
(function () {
  var STORE = '80742134', API = 'api.salla.dev';

  // 1) Store-Identifier header on every Salla API request
  try {
    if (window.fetch) {
      var _fetch = window.fetch;
      window.fetch = function (input, init) {
        try {
          var url = typeof input === 'string' ? input : (input && input.url) || '';
          if (url.indexOf(API) > -1) {
            init = init || {};
            var h = new Headers(init.headers || (input && input.headers) || {});
            if (!h.has('Store-Identifier')) h.set('Store-Identifier', STORE);
            init.headers = h;
          }
        } catch (e) {}
        return _fetch.call(this, input, init);
      };
    }
    var P = XMLHttpRequest.prototype, _open = P.open, _send = P.send, _set = P.setRequestHeader;
    P.open = function (m, u) { this.__sApi = String(u).indexOf(API) > -1; this.__sHas = false; return _open.apply(this, arguments); };
    P.setRequestHeader = function (k, v) { if (String(k).toLowerCase() === 'store-identifier') this.__sHas = true; return _set.apply(this, arguments); };
    P.send = function () { try { if (this.__sApi && !this.__sHas) _set.call(this, 'Store-Identifier', STORE); } catch (e) {} return _send.apply(this, arguments); };
  } catch (e) {}

  // 2) Strip ?scope= from cart links / current URL
  function cleanUrl(u) {
    try {
      var x = new URL(u, location.href);
      if (/\/cart\/?$/.test(x.pathname) && x.searchParams.has('scope')) { x.searchParams.delete('scope'); return x.toString(); }
    } catch (e) {}
    return null;
  }

  // 3) Hide the one toast
  function run() {
    var c = cleanUrl(location.href); if (c) history.replaceState(null, '', c);
    document.querySelectorAll('a[href*="cart"]').forEach(function (a) { var n = cleanUrl(a.href); if (n) a.href = n; });
    document.querySelectorAll('.s-toast,[class*="toast"],[class*="notif"]').forEach(function (t) {
      if (/Store Identifier not found/i.test(t.textContent || '')) t.style.display = 'none';
    });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
  new MutationObserver(run).observe(document.documentElement, { childList: true, subtree: true });
})();