(function () {
  // Set global flag for pixel detection
  window.__BULLSEYE_PIXEL_LOADED__ = true;
  window.__BULLSEYE_API_KEY__ = "935851dd-0c1a-4867-abda-092a70812aff";
  
  console.debug("bullseye script loaded");

  // ============================================================================
  // PRIVACY SIGNAL DETECTION (GPC & DNT)
  // ============================================================================
  // Check for Global Privacy Control (GPC) signal
  const hasGPC = navigator.globalPrivacyControl === true;
  
  // Check for Do Not Track (DNT) signal (legacy support)
  const hasDNT = navigator.doNotTrack === "1" || 
                 window.doNotTrack === "1" ||
                 navigator.msDoNotTrack === "1";
  
  // Check for local opt-out preference
  const hasLocalOptOut = localStorage.getItem("bullseye_privacy_opt_out") === "true";
  
  // Honor privacy signals - exit early if any signal is detected
  if (hasGPC || hasDNT || hasLocalOptOut) {
    const signalType = hasGPC ? "GPC" : (hasDNT ? "DNT" : "Local Opt-Out");
    
    // Expose opt-in function for users who want to re-enable tracking
    window.bullseyeOptIn = function() {
      localStorage.removeItem("bullseye_privacy_opt_out");
      return true;
    };
    
    // Expose opt-out function for manual privacy preference
    window.bullseyeOptOut = function() {
      localStorage.setItem("bullseye_privacy_opt_out", "true");
      return true;
    };
    
    return; // Exit script - no tracking will occur
  }
  
  // Expose opt-out function for users
  window.bullseyeOptOut = function() {
    localStorage.setItem("bullseye_privacy_opt_out", "true");
    return true;
  };
  
  // ============================================================================
  // DOMAIN VALIDATION
  // ============================================================================
  // Check if current domain is in the allowed domains list
  // This prevents tracking (and credit consumption) on unauthorized domains
  const allowedDomains = ["acmestud.io","shipped.digital","vibemarket.ing"];
  
  // If no allowed domains configured, block script execution
  if (!allowedDomains || allowedDomains.length === 0) {
    console.warn("[Bullseye] No allowed domains configured");
    return;
  }
  
  const currentHostname = window.location.hostname.toLowerCase();
  
  // Check if current domain matches any allowed domain
  // Handles www/non-www variants automatically
  const isDomainAllowed = allowedDomains.some(function(allowed) {
    allowed = allowed.toLowerCase()
      .replace(/^https?:\/\//, '')  // Remove protocol
      .replace(/\/.*$/, '');         // Remove path
    
    // Direct match
    if (currentHostname === allowed || currentHostname.endsWith('.' + allowed)) {
      return true;
    }
    
    // Handle www variants
    const allowedWithoutWww = allowed.replace(/^www\./, '');
    const currentWithoutWww = currentHostname.replace(/^www\./, '');
    
    return currentWithoutWww === allowedWithoutWww || 
           currentWithoutWww.endsWith('.' + allowedWithoutWww);
  });
  
  if (!isDomainAllowed) {
    console.warn("[Bullseye] Domain not authorized for tracking:", currentHostname);
    return; // Exit script - no tracking or integrations will occur
  }
  
  // ============================================================================

  const sessionKey = "be_session";
  let shouldIntegrateEnhancedScript = true;

  // Initialize the app - handle session creation based on integrations
  initializeApp();

  async function initializeApp() {
    let session;
    
    // Check if we need to wait for enhanced session cookie
    if (shouldIntegrateEnhancedScript) {
      // Load the enhanced tracking script first
      integrateEnhancedTrackingScript();
      
      // Wait for the session cookie to be set by the enhanced tracking script
      const enhancedSessionId = await waitForEnhancedSessionId();
      
      if (enhancedSessionId) {
        console.debug("[Bullseye] Using enhanced session ID:", enhancedSessionId);
        session = JSON.parse(localStorage.getItem(sessionKey));
        if (!session || isExpire(session.expiresAt) || session.id !== enhancedSessionId) {
          session = createSession(enhancedSessionId);
        }
      } else {
        // Fallback if cookie not set after timeout
        console.debug("[Bullseye] Enhanced session ID not found, using random UUID");
        session = JSON.parse(localStorage.getItem(sessionKey));
        if (!session || isExpire(session.expiresAt)) {
          session = createSession(crypto.randomUUID());
        }
      }
    } else {
      // Standard flow - no enhanced tracking integration
      session = JSON.parse(localStorage.getItem(sessionKey));
      if (!session || isExpire(session.expiresAt)) {
        session = createSession(crypto.randomUUID());
      }
    }

    session.apiKey = "935851dd-0c1a-4867-abda-092a70812aff";

    let shouldIntegrateVendor1Script = true;
    if (shouldIntegrateVendor1Script) {
      integrateVendor1Script(JSON.stringify(session));
    }

    reactOnPageChanges(false, session);

    let shouldIntegrateVendor2Script = true;
    if (shouldIntegrateVendor2Script) {
      integrateVendor2Script(JSON.stringify(session));
    }
  }

  function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
      return parts.pop().split(';').shift();
    }
    return null;
  }

  function waitForEnhancedSessionId(maxWaitTime = 5000, checkInterval = 100) {
    return new Promise((resolve) => {
      const startTime = Date.now();
      
      const checkCookie = () => {
        const sessionId = getCookie('vv_session_id');
        
        if (sessionId) {
          resolve(sessionId);
          return;
        }
        
        if (Date.now() - startTime >= maxWaitTime) {
          resolve(null);
          return;
        }
        
        setTimeout(checkCookie, checkInterval);
      };
      
      checkCookie();
    });
  }

  function createSession(clientSessionID) {
    const session = {
      id: clientSessionID,
      expiresAt: new Date(Date.now() + 5 * 60 * 1000).getTime(),
    };

    const JSONSession = JSON.stringify(session);
    localStorage.setItem(sessionKey, JSONSession);

    return session;
  }

  function isExpire(expiresAt) {
    return new Date(expiresAt) <= new Date();
  }

  function reactOnPageChanges(requestAlreadySent, session) {
    setInterval(() => {
      const currentPath = window.location.pathname;
      if (currentPath !== window.lastPath) {
        window.lastPath = currentPath;
        console.debug("page changed:", window.location.pathname);

        if (requestAlreadySent) {
          requestAlreadySent = false;
        } else {
          trackSession(session.id);
        }
      }
    }, 500);
  }

  function integrateVendor2Script(sessionData) {
    var cookie_sync = document.createElement("script");
    cookie_sync.src = `https://a.usbrowserspeed.com/cs?pid=d6e515d0ce492cc3ed73a406e2fab033e8a10636ef3d46b45e892ea62beca33f&puid=${sessionData}`;
    cookie_sync.type = "text/javascript";
    document.head.appendChild(cookie_sync);
  }

  function integrateEnhancedTrackingScript() {
    var scriptUrl = "https://data.processwebsitedata.com/cscripts/EBkHRbrbFS-3bf992c0.js";
    if (scriptUrl && scriptUrl !== '') {
      try {
        var script = document.createElement('script');
        script.src = scriptUrl;
        script.defer = true;
        script.type = 'text/javascript';
        document.head.appendChild(script);
      } catch (err) {
        console.error("Error integrating script:", err);
      }
    }
  }

  async function integrateVendor1Script(sessionData) {
    // Set partnerId before loading Vector (stringified as required)
    // This ensures partnerId is available 100% of the time
    window.vector = window.vector || {};
    window.vector.partnerId = sessionData; // sessionData is already stringified

    !(function (e, r) {
      try {
        if (e.vector && e.vector.loaded)
          return void console.log("snippet included more than once.");
        var t = e.vector || {};
        t.q = t.q || [];
        for (
          var o = ["load", "identify", "on"],
            n = function (e) {
              return function () {
                var r = Array.prototype.slice.call(arguments);
                t.q.push([e, r]);
              };
            },
            c = 0;
          c < o.length;
          c++
        ) {
          var a = o[c];
          t[a] = n(a);
        }
        if (((e.vector = t), !t.loaded)) {
          var i = r.createElement("script");
          (i.type = "text/javascript"),
            (i.async = !0),
            (i.src = "https://cdn.vector.co/pixel.js");
          var l = r.getElementsByTagName("script")[0];
          l.parentNode.insertBefore(i, l), (t.loaded = !0);
        }
      } catch (e) {
        console.error("Error loading:", e);
      }
    })(window, document);

    try {
      await vector.load("c000fa50-57c2-466f-8d13-b10b8b363e98");
      // Keep identify() temporarily to fill gaps for visitors who may have missing data
      // This is now redundant but helps with backward compatibility during transition
      await vector.identify(sessionData);
    } catch (err) {
      console.error(err);
    }
  }

  async function trackSession(clientSessionID) {
    try {
      const response = await fetch("https://api.app.bullseye.so/api/v1/visitor-tracking/track", {
        method: "POST",
        body: JSON.stringify({
          clientSessionId: clientSessionID,
          apiKey: "935851dd-0c1a-4867-abda-092a70812aff",
          url: window.location.href,
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
      });
      const json = await response.json();
      console.log(json);
    } catch (err) {
      console.error(err);
    }
  }
})();
