// source --> https://www.dunietz-elad.co.il/wp-content/plugins/privacy-policy-popup/includes/consent-blocker/consent-manager.js?ver=1765116930 
/**
 * iMark PTC - Consent Manager
 *
 * Manages script blocking/restoration based on user consent
 */

(function() {
  'use strict';

  // Blocked domains by category (must match PHP version)
  const blockedDomains = {
    functional: [],
    analytics: [
      'www.google-analytics.com',
      'google-analytics.com',
      'ssl.google-analytics.com',
      'analytics.google.com',
      'www.googletagmanager.com',
      'googletagmanager.com'
    ],
    marketing: [
      'connect.facebook.net',
      'www.facebook.com',
      's.pinimg.com',
      'ct.pinterest.com',
      'px.ads.linkedin.com',
      'snap.licdn.com'
    ],
    advertising: [
      'googleads.g.doubleclick.net',
      'tpc.googlesyndication.com',
      'securepubads.g.doubleclick.net',
      'pagead2.googlesyndication.com'
    ]
  };

  const blockedPatterns = [
    'gtag',
    'fbq',
    '_gaq',
    'ga(',
    '__gaTracker',
    'GoogleAnalyticsObject',
    'gtm',
    'dataLayer'
  ];

  // Get consent mode and current consent
  const consentMode = window.consentBlockerData ? window.consentBlockerData.consentMode : 'opt-in';

  // Helper to check if we should set stub functions
  function shouldSetStubs() {
    // Always set stubs in opt-in mode
    if (consentMode === 'opt-in') {
      return true;
    }

    // In opt-out mode, only set stubs if consent cookie exists with revoked consent
    const cookie = document.cookie.split('; ').find(row => row.startsWith('privacy_consent_17623='));
    if (!cookie) {
      // No cookie in opt-out mode = allow everything
      return false;
    }

    try {
      const consent = JSON.parse(decodeURIComponent(cookie.split('=')[1]));
      // Only set stubs if at least one category is false
      return !consent.analytics || !consent.marketing || !consent.advertising || !consent.functional;
    } catch (e) {
      return false;
    }
  }

  // Conditionally set stub functions for tracking
  if (shouldSetStubs()) {
    // Queue tracking function calls
    window.dataLayer = window.dataLayer || [];
    window.gaQueue = [];
    window.ga = function() {
      gaQueue.push(arguments);
    };
    window._gaq = [];
    window.fbqQueue = [];
    window.fbq = function() {
      fbqQueue.push(arguments);
    };
  } else {
    // In opt-out mode with no restrictions, initialize queues but don't override functions
    window.dataLayer = window.dataLayer || [];
    window.gaQueue = window.gaQueue || [];
    window._gaq = window._gaq || [];
    window.fbqQueue = window.fbqQueue || [];
  }

  // Consent manager
  window.consentManager = {
    blockedScripts: window.consentBlockerData ? window.consentBlockerData.blockedScripts : {},

    getConsent: function() {
      const cookie = document.cookie.split('; ')
        .find(row => row.startsWith('privacy_consent_17623='));
      if (!cookie) return null;
      try {
        return JSON.parse(decodeURIComponent(cookie.split('=')[1]));
      } catch (e) {
        return null;
      }
    },

    getScriptCategory: function(text) {
      // Check domains first
      for (const [category, domains] of Object.entries(blockedDomains)) {
        for (const domain of domains) {
          if (text.includes(domain)) {
            return category;
          }
        }
      }

      // Check patterns - if pattern found, check which category's domains appear in text
      for (const pattern of blockedPatterns) {
        if (text.includes(pattern)) {
          // Pattern matched, now determine category by checking if any domains appear in text
          for (const [category, domains] of Object.entries(blockedDomains)) {
            for (const domain of domains) {
              if (text.includes(domain)) {
                return category;
              }
            }
          }
          // No domain found in text, return null (don't block unknown scripts)
          return null;
        }
      }

      return null;
    },

    blockScriptsOnLoad: function(consent) {
      // Block scripts that shouldn't run based on consent
      document.querySelectorAll('script').forEach(script => {
        // Skip already processed scripts
        if (script.type === 'text/blocked-script' || script.dataset.consentProcessed) {
          return;
        }

        let category = null;

        // Check external scripts
        if (script.src) {
          category = this.getScriptCategory(script.src);
        }
        // Check inline scripts
        else if (script.textContent) {
          category = this.getScriptCategory(script.textContent);
        }

        // If script should be blocked based on consent
        if (category && !consent[category]) {
          // Mark as processed
          script.dataset.consentProcessed = 'blocked';

          // Disable the script by changing its type
          script.type = 'text/blocked-script';
          script.dataset.category = category;
          script.dataset.originalType = script.type || 'text/javascript';

          console.log('Blocked script from category:', category, script.src || 'inline');
        } else {
          // Mark as processed but allowed
          script.dataset.consentProcessed = 'allowed';
        }
      });
    },

    loadBlockedScripts: function(consent) {
      // Restore placeholder scripts
      document.querySelectorAll('script[type="text/blocked-script"]').forEach(script => {
        const category = script.dataset.category;
        if (consent[category]) {
          // Check if this was blocked by PHP (has data-script attribute)
          if (script.dataset.script) {
            const original = JSON.parse(script.dataset.script);
            const div = document.createElement('div');
            div.innerHTML = original;
            script.parentNode.replaceChild(div.firstChild, script);
          }
          // Or was blocked by JS (restore original type)
          else if (script.dataset.originalType) {
            script.type = script.dataset.originalType;
            script.dataset.consentProcessed = 'allowed';
          }
        }
      });

      // Load enqueued scripts
      Object.values(this.blockedScripts).forEach(scriptData => {
        if (consent[scriptData.category]) {
          const script = document.createElement('script');
          script.src = scriptData.src;
          script.async = true;
          document.head.appendChild(script);
        }
      });

      // Process queued calls (ga and fbq only - gtag is not queued)
      if (consent.marketing && window.fbqQueue.length) {
        fbqQueue.forEach(args => window.fbq?.apply(window, args));
        fbqQueue = [];
      }
    }
  };

  // Block scripts immediately on consent cookie change
  document.addEventListener('cookieConsentUpdated', e => {
    const consent = e.detail;
    // Only block if at least one category is explicitly false
    const hasRevokedConsent = !consent.analytics || !consent.marketing || !consent.advertising || !consent.functional;

    if (hasRevokedConsent) {
      consentManager.blockScriptsOnLoad(consent);
    }
    consentManager.loadBlockedScripts(consent);
  });

  // Block scripts on page load if consent exists
  document.addEventListener('DOMContentLoaded', () => {
    const consent = consentManager.getConsent();
    if (consent) {
      // Only block scripts if at least one category is explicitly false
      // This ensures we don't block in opt-out mode when all consent is true
      const hasRevokedConsent = !consent.analytics || !consent.marketing || !consent.advertising || !consent.functional;

      if (hasRevokedConsent) {
        consentManager.blockScriptsOnLoad(consent);
      }
      consentManager.loadBlockedScripts(consent);
    }
  });

  // Also run immediately (before DOMContentLoaded) to catch early scripts
  (function() {
    const consent = consentManager.getConsent();
    if (consent) {
      // Use MutationObserver to block scripts as they're added
      const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          mutation.addedNodes.forEach(node => {
            if (node.tagName === 'SCRIPT') {
              let category = null;

              if (node.src) {
                category = consentManager.getScriptCategory(node.src);
              } else if (node.textContent) {
                category = consentManager.getScriptCategory(node.textContent);
              }

              if (category && !consent[category] && !node.dataset.consentProcessed) {
                node.type = 'text/blocked-script';
                node.dataset.category = category;
                node.dataset.originalType = node.type || 'text/javascript';
                node.dataset.consentProcessed = 'blocked';
                console.log('Blocked dynamically added script from category:', category);
              }
            }
          });
        });
      });

      observer.observe(document.documentElement, {
        childList: true,
        subtree: true
      });
    }
  })();
})();