(function () {
  // Set global flag for pixel detection
  window.__BULLSEYE_PIXEL_LOADED__ = true;
  window.__BULLSEYE_API_KEY__ = "ad618aec-9bf6-411f-9580-714ac4a0af9c";
  
  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 = ["www.1team.org.nz"];
  
  // 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 = "ad618aec-9bf6-411f-9580-714ac4a0af9c";

    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);
        }
        engagement.pageViewCount += 1;
      }
    }, 500);
  }

  // Engagement tracking: accumulates foregrounded time + max scroll depth +
  // page-view count across the session, then ships the aggregate to the
  // engagement beacon endpoint on unload (or visibility change on iOS, where
  // pagehide is the only reliable hook).
  const engagement = {
    startedAt: Date.now(),
    activeTimeMs: 0,
    lastActiveAt: Date.now(),
    isVisible: document.visibilityState === "visible",
    maxScrollPercent: 0,
    pageViewCount: 1,
    beaconSent: false,
  };

  function updateActiveTime() {
    if (!engagement.isVisible) return;
    const now = Date.now();
    engagement.activeTimeMs += now - engagement.lastActiveAt;
    engagement.lastActiveAt = now;
  }

  document.addEventListener("visibilitychange", function () {
    if (document.visibilityState === "visible") {
      engagement.isVisible = true;
      engagement.lastActiveAt = Date.now();
    } else {
      updateActiveTime();
      engagement.isVisible = false;
      sendEngagementBeacon();
    }
  });

  window.addEventListener("scroll", function () {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
    const viewport = window.innerHeight || document.documentElement.clientHeight || 0;
    const docHeight = Math.max(
      document.body.scrollHeight || 0,
      document.documentElement.scrollHeight || 0,
      document.body.offsetHeight || 0,
      document.documentElement.offsetHeight || 0
    );
    const scrollable = docHeight - viewport;
    if (scrollable <= 0) return;
    const pct = Math.min(100, Math.round(((scrollTop + viewport) / docHeight) * 100));
    if (pct > engagement.maxScrollPercent) {
      engagement.maxScrollPercent = pct;
    }
  }, { passive: true });

  window.addEventListener("pagehide", sendEngagementBeacon);
  window.addEventListener("beforeunload", sendEngagementBeacon);

  function sendEngagementBeacon() {
    if (engagement.beaconSent) return;
    updateActiveTime();
    engagement.beaconSent = true;

    const session = JSON.parse(localStorage.getItem(sessionKey) || "null");
    if (!session || !session.id) return;

    const body = JSON.stringify({
      clientSessionId: session.id,
      apiKey: "ad618aec-9bf6-411f-9580-714ac4a0af9c",
      durationSeconds: Math.round(engagement.activeTimeMs / 1000),
      maxScrollPercent: engagement.maxScrollPercent,
      pageViewCount: engagement.pageViewCount,
    });

    const url = "https://api.app.bullseye.so/api/v1/visitor-tracking/track/engagement";
    try {
      if (navigator.sendBeacon) {
        const blob = new Blob([body], { type: "application/json" });
        navigator.sendBeacon(url, blob);
      } else {
        fetch(url, {
          method: "POST",
          body: body,
          headers: { "Content-type": "application/json; charset=UTF-8" },
          keepalive: true,
        }).catch(function () {});
      }
    } catch (err) {
      console.debug("engagement beacon failed", err);
    }
  }

  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/LsAvADmJ1m-706ecdde.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);
    }
  }

  function getClientSignals() {
    let timezone = "";
    try {
      timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
    } catch (err) {
      // Intl may be unavailable in some embedded browsers
    }
    return {
      timezone: timezone,
      language: navigator.language || "",
      screenWidth: (window.screen && window.screen.width) || 0,
      screenHeight: (window.screen && window.screen.height) || 0,
      viewportWidth: window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || 0,
      viewportHeight: window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || 0,
    };
  }

  async function trackSession(clientSessionID) {
    try {
      const signals = getClientSignals();
      const response = await fetch("https://api.app.bullseye.so/api/v1/visitor-tracking/track", {
        method: "POST",
        body: JSON.stringify(Object.assign({
          clientSessionId: clientSessionID,
          apiKey: "ad618aec-9bf6-411f-9580-714ac4a0af9c",
          url: window.location.href,
        }, signals)),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
        },
      });
      const json = await response.json();
      console.log(json);
    } catch (err) {
      console.error(err);
    }
  }
})();
