/* Disable legacy Smart Observer only on completed-order pages. */
(() => {
  if (!/\/thankyou(?:\/|$)/.test(window.location.pathname)) return;

  const observerEndpoint = 'https://observer.marketing/event';
  const observerScript = 'client-do9.pages.dev/index.js';

  // Prevent the legacy client from starting on the order receipt page.
  window.__sallaObserverLoaded = true;

  // Remove its script if another inline integration tries to append it.
  const removeLegacyScript = (node) => {
    if (node && node.tagName === 'SCRIPT' && String(node.src).includes(observerScript)) {
      node.remove();
    }
  };
  document.querySelectorAll('script[src*="client-do9.pages.dev/index.js"]').forEach(removeLegacyScript);
  new MutationObserver((records) => {
    records.forEach((record) => record.addedNodes.forEach(removeLegacyScript));
  }).observe(document.documentElement, { childList: true, subtree: true });

  // Final safeguard: block only PURCHASE requests to Smart Observer.
  const nativeFetch = window.fetch;
  if (typeof nativeFetch === 'function' && !nativeFetch.__blocksObserverPurchase) {
    function guardedFetch(input, init) {
      try {
        const url = typeof input === 'string' ? input : input && input.url;
        if (url === observerEndpoint && init && init.body) {
          const payload = JSON.parse(init.body);
          if (payload && payload.event && payload.event.name === 'purchase') {
            return Promise.resolve(new Response(null, { status: 204 }));
          }
        }
      } catch (_) {}
      return nativeFetch.apply(this, arguments);
    }
    guardedFetch.__blocksObserverPurchase = true;
    window.fetch = guardedFetch;
  }
})();