
    (function() {
      console.log("Frndly tracking script loaded at", new Date().toISOString());
      
      // Use hardcoded endpoint instead of dynamic detection
      var workerEndpoint = "https://tag.frndlytv.com";
      
      console.log("Worker endpoint determined:", workerEndpoint);
      
      // Generate a client ID if not already present
      function getClientId() {
        var storageKey = 'ga_client_id';
        var existingId = localStorage.getItem(storageKey);
        
        if (existingId) {
          return existingId;
        }
        
        // Generate a new client ID
        var newId = Math.floor(Math.random() * 1000000000) + '.' + Math.floor(Date.now() / 1000);
        localStorage.setItem(storageKey, newId);
        return newId;
      }

      // Get the viewport size
      function getViewportSize() {
        return window.innerWidth + 'x' + window.innerHeight;
      }

      // Get the screen resolution
      function getScreenResolution() {
        return screen.width + 'x' + screen.height;
      }
      
      // Get session information
      function getSessionInfo() {
        var sessionKey = 'ga_session_id';
        var sessionCountKey = 'ga_session_count';
        var sessionTimeout = 30 * 60 * 1000; // 30 minutes
        
        var sessionId = sessionStorage.getItem(sessionKey);
        var lastActivity = parseInt(sessionStorage.getItem('ga_last_activity') || '0');
        var sessionCount = parseInt(localStorage.getItem(sessionCountKey) || '0');
        var now = Date.now();
        
        // If session expired or doesn't exist, create a new one
        if (!sessionId || (now - lastActivity > sessionTimeout)) {
          sessionId = now.toString();
          sessionStorage.setItem(sessionKey, sessionId);
          sessionCount++;
          localStorage.setItem(sessionCountKey, sessionCount.toString());
        }
        
        // Update last activity
        sessionStorage.setItem('ga_last_activity', now.toString());
        
        return {
          session_id: sessionId,
          session_number: sessionCount
        };
      }
      
      // Get all Google conversion cookies
      function getGoogleConversionCookies() {
        var cookies = {};
        
        // Get all cookies
        document.cookie.split(';').forEach(function(cookie) {
          var parts = cookie.trim().split('=');
          var name = parts[0];
          var value = parts.slice(1).join('='); // Handle values that might contain =
          
          // Capture all Google conversion-related cookies
          if (name.startsWith('_gcl_') || 
              name.startsWith('FPGCL') || 
              name.startsWith('_ga') || 
              name.startsWith('FPLC')) {
            cookies[name] = value;
          }
        });
        
        console.log('Google conversion cookies found:', cookies);
        return cookies;
      }
      
      // Parse URL parameters and set proper cookies
      function getUrlParams() {
        var result = {};
        var urlParams = new URLSearchParams(window.location.search);
        
        // Campaign parameters
        var campaignParams = [
          'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 
          'gclid', 'fbclid', 'cjevent', 'msclkid', 'ref'
        ];
        
        campaignParams.forEach(function(param) {
          var value = urlParams.get(param);
          if (value) {
            result[param] = value;
            
            // Store in localStorage as backup
            localStorage.setItem(param, value);
            
            // Set as cookies with proper domain
            if (param === 'gclid') {
              // Google Ads requires specific cookie format
              document.cookie = `_gcl_aw=1.${Date.now()}.${value}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
              
              // Also create first-party cookies for conversion linker
              try {
                // Set Google's first-party conversion cookies
                // This is where the Google Ads JS would normally store first-party cookies needed for conversion attribution
                document.cookie = `FPGCLAW_${value}=1.${Date.now()}.${value}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
                document.cookie = `FPLC=${Date.now()}.${value}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
              } catch(e) {
                console.error('Error setting conversion cookies:', e);
              }
            } else if (param === 'fbclid') {
              document.cookie = `_fbc=fb.1.${Date.now()}.${value}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
              // Also set _fbp cookie if it doesn't exist
              if (!document.cookie.match(/(^|;)\s*_fbp=/)) {
                document.cookie = `_fbp=fb.1.${Date.now()}.${Math.floor(Math.random() * 10000000000)}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
              }
            } else {
              document.cookie = `${param}=${value}; domain=.frndlytv.com; path=/; max-age=7776000; SameSite=None; Secure`;
            }
          } else {
            // Check cookies if not in URL
            var cookieMatch = document.cookie.match(new RegExp('(^| )' + param + '=([^;]+)'));
            if (cookieMatch) result[param] = cookieMatch[2];
            
            // For Google Ads, check _gcl_aw cookie format
            if (param === 'gclid' && !result[param]) {
              cookieMatch = document.cookie.match(new RegExp('(^| )_gcl_aw=([^;]+)'));
              if (cookieMatch) {
                var parts = cookieMatch[2].split('.');
                if (parts.length >= 3) {
                  result[param] = parts[2]; // Extract actual gclid from cookie
                }
              }
            }
            
            // For Facebook, check _fbc cookie format
            if (param === 'fbclid' && !result[param]) {
              cookieMatch = document.cookie.match(new RegExp('(^| )_fbc=([^;]+)'));
              if (cookieMatch && cookieMatch[2].startsWith('fb.1.')) {
                var parts = cookieMatch[2].split('.');
                if (parts.length >= 3) {
                  result[param] = parts[2]; // Extract actual fbclid from cookie
                }
              }
            }
          }
        });
        
        return result;
      }
      
      // Send event to GA4 via server GTM
      function sendEvent(eventType, eventParams, userProperties) {
        // Get session information
        var sessionInfo = getSessionInfo();
        
        // Base payload with all required GA4 parameters
        var payload = {
          event: eventType || 'page_view',
          client_id: getClientId(),
          
          // Page parameters
          page_location: window.location.href,
          page_title: document.title,
          page_referrer: document.referrer,
          
          // Technical parameters
          user_agent: navigator.userAgent,
          language: navigator.language || 'en-us',
          screen_resolution: getScreenResolution(),
          viewport_size: getViewportSize(),
          timestamp: new Date().toISOString(),
          
          // Session parameters
          session_id: sessionInfo.session_id,
          session_number: sessionInfo.session_number,
          
          // For page_view events, calculate engagement time if possible
          engagement_time_msec: (eventType === 'page_view' && window.performance) 
            ? Math.round(performance.now()) 
            : undefined,
          
          // Origin for headers
          origin: window.location.origin,
          
          // URL parameters (UTM, etc.)
          ...getUrlParams(),
          
          // Google conversion cookies
          google_conversion_cookies: getGoogleConversionCookies(),
          
          // Add Google Consent Mode values
          consent_mode: {
            analytics_storage: hasConsentForTracking() ? 'granted' : 'denied',
            ad_storage: hasConsentForMarketing() ? 'granted' : 'denied',
            personalization_storage: hasConsentForPreferences() ? 'granted' : 'denied',
            functionality_storage: 'granted', // Always granted as it's essential
            security_storage: 'granted'  // Always granted as it's essential
          }
        };
        
        // Add custom event parameters
        if (eventParams && typeof eventParams === 'object') {
          payload.params = eventParams;
        }
        
        // Add user properties
        if (userProperties && typeof userProperties === 'object') {
          payload.user_properties = userProperties;
        }
        
        // Add debugging logs for ALL events
        console.log('Sending event to server:', eventType);
        console.log('Event payload:', JSON.stringify(payload, null, 2));
        console.log('Consent status - Analytics:', payload.consent_mode.analytics_storage);
        console.log('Consent status - Ads:', payload.consent_mode.ad_storage);
        console.log('Consent status - Personalization:', payload.consent_mode.personalization_storage);
        
        // Send to our Cloudflare Worker
        return fetch(workerEndpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
          // Use keepalive for events sent during page unload
          keepalive: true
        })
        .then(function(response) {
          if (!response.ok) {
            throw new Error('Server responded with status: ' + response.status);
          }
          return response.json();
        })
        .then(function(responseData) {
          // Log the server response
          console.log('Server response for ' + eventType + ' event:', responseData);
          return responseData;
        })
        .catch(function(error) {
          console.error('Error sending ' + eventType + ' event:', error);
          throw error;
        });
      }
      
      // Check if user has given consent for tracking (analytics)
      function hasConsentForTracking() {
        // First check if window.PrivacyConsent exists (from privacy-worker.js)
        if (window.PrivacyConsent && window.PrivacyConsent.getConsent) {
          const consent = window.PrivacyConsent.getConsent();
          // For analytics events, we need analytics consent
          return consent.analytics === true;
        }
        
        // If privacy consent system isn't available, check cookies directly
        try {
          const analyticsCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('consent_analytics='));
            
          if (analyticsCookie) {
            return analyticsCookie.split('=')[1] === 'true';
          }
          
          // Check for GPC signal which would deny consent
          const gpcCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('frndly_privacy_doNotSell='));
            
          if (gpcCookie && gpcCookie.split('=')[1] === 'true') {
            return false; // GPC signal is present, deny tracking
          }
        } catch (e) {
          console.warn('Error checking consent cookies:', e);
        }
        
        // Default to false if we can't determine consent status
        // This is the privacy-safe default
        return false;
      }
      
      // Check if user has given consent for marketing
      function hasConsentForMarketing() {
        // First check if window.PrivacyConsent exists (from privacy-worker.js)
        if (window.PrivacyConsent && window.PrivacyConsent.getConsent) {
          const consent = window.PrivacyConsent.getConsent();
          return consent.marketing === true;
        }
        
        // If privacy consent system isn't available, check cookies directly
        try {
          const marketingCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('consent_marketing='));
            
          if (marketingCookie) {
            return marketingCookie.split('=')[1] === 'true';
          }
          
          // Check for GPC signal which would deny consent
          const gpcCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('frndly_privacy_doNotSell='));
            
          if (gpcCookie && gpcCookie.split('=')[1] === 'true') {
            return false; // GPC signal is present, deny marketing
          }
        } catch (e) {
          console.warn('Error checking consent cookies:', e);
        }
        
        // Default to false if we can't determine consent status
        return false;
      }
      
      // Check if user has given consent for preferences
      function hasConsentForPreferences() {
        // First check if window.PrivacyConsent exists (from privacy-worker.js)
        if (window.PrivacyConsent && window.PrivacyConsent.getConsent) {
          const consent = window.PrivacyConsent.getConsent();
          return consent.preferences === true;
        }
        
        // If privacy consent system isn't available, check cookies directly
        try {
          const preferencesCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('consent_preferences='));
            
          if (preferencesCookie) {
            return preferencesCookie.split('=')[1] === 'true';
          }
          
          // Check for GPC signal which would deny consent
          const gpcCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('frndly_privacy_doNotSell='));
            
          if (gpcCookie && gpcCookie.split('=')[1] === 'true') {
            return false; // GPC signal is present, deny preferences
          }
        } catch (e) {
          console.warn('Error checking consent cookies:', e);
        }
        
        // Default to false if we can't determine consent status
        return false;
      }
      
      // In the tracking script
      function sendPurchase(transactionData) {
        if (!transactionData) {
          console.error('Transaction data is required for purchase events');
          return Promise.reject(new Error('Transaction data is required'));
        }
        
        // Clone the data to avoid modifying the original
        const purchaseData = {
          event: 'purchase',
          transaction_id: transactionData.transactionId || transactionData.transaction_id,
          value: transactionData.transactionTotal || transactionData.value || transactionData.revenue,
          currency: transactionData.currency || 'USD',
          reference_id: transactionData.referenceId || transactionData.reference_id,
          frndly_id: transactionData.frndlyId || transactionData.frndly_id
        };
        
        // Add items directly to the root object
        if (transactionData.transactionProducts || transactionData.items) {
          purchaseData.items = transactionData.transactionProducts || transactionData.items;
        }

        // Add user ID directly to the root, not nested in user_properties
        if (transactionData.userId || transactionData.user_id) {
          purchaseData.user_id = transactionData.userId || transactionData.user_id;
        }
        
        // Add Google conversion cookies specifically for purchase events
        purchaseData.google_conversion_cookies = getGoogleConversionCookies();
        
        // Log the full purchase payload for debugging
        console.log('Purchase payload:', JSON.stringify(purchaseData, null, 2));
        console.log('Google conversion cookies for purchase:', purchaseData.google_conversion_cookies);
        
        // Send as a regular event but with the special purchase data structure
        return sendEvent('purchase', purchaseData);
      }
      
      // Track page visibility changes
      function setupVisibilityTracking() {
        var startTime, visibilityTime = 0;
        
        document.addEventListener('visibilitychange', function() {
          if (document.visibilityState === 'visible') {
            startTime = Date.now();
          } else if (startTime) {
            visibilityTime += (Date.now() - startTime);
            startTime = null;
            
            // Send engagement event if significant time was spent on page
            if (visibilityTime > 1000) { // Consent check removed
              sendEvent('user_engagement', {
                engagement_time_msec: visibilityTime
              });
              visibilityTime = 0;
            }
          }
        });
      }
      
      // Set up click tracking for key elements
      function setupClickTracking() {
        document.addEventListener('click', function(e) {
          var target = e.target;
          
          // Track link clicks
          if (target.tagName === 'A' || target.closest('a')) {
            var link = target.tagName === 'A' ? target : target.closest('a');
            var href = link.href || '';
            
            if (href && !href.startsWith('javascript:')) {
              // Consent check removed
              sendEvent('click', {
                link_url: href,
                link_id: link.id || undefined,
                  link_classes: link.className || undefined,
                  link_text: link.innerText || link.textContent || undefined,
                  outbound: link.hostname !== window.location.hostname
                });
              }
          } // <-- CORRECT PLACEMENT for link click block

          // Track button clicks
          if (target.tagName === 'BUTTON' || target.closest('button') ||
              (target.tagName === 'INPUT' && target.type === 'button') ||
              target.getAttribute('role') === 'button') {
            var button = target.tagName === 'BUTTON' || (target.tagName === 'INPUT' && target.type === 'button')
                        ? target : target.closest('button') || target;

            // Consent check removed
            sendEvent('click', {
              button_id: button.id || undefined,
              button_name: button.name || undefined,
              button_text: button.innerText || button.textContent || button.value || undefined
            });
          } // <-- CORRECT PLACEMENT for button click block
        }); // This closes the addEventListener callback
      } // This closes setupClickTracking
      
      // Set up form submission tracking
      function setupFormTracking() {
        document.addEventListener('submit', function(e) {
          var form = e.target;
          
          if (form.tagName === 'FORM') {
            // Consent check removed
            sendEvent('form_submit', {
              form_id: form.id || undefined,
              form_name: form.name || undefined,
                form_classes: form.className || undefined,
                form_destination: form.action || undefined
              });
            }
        });
      }
      
      // NEW FUNCTION: Add this function to monitor the dataLayer
      function setupDataLayerMonitoring() {
        // Initialize dataLayer if it doesn't exist
        window.dataLayer = window.dataLayer || [];
        
        console.log('Setting up dataLayer monitoring for transaction events');
        console.log('Current dataLayer state:', JSON.stringify(window.dataLayer));
        
        // Process any existing events in the dataLayer
        if (window.dataLayer.length > 0) {
          window.dataLayer.forEach(function(event, index) {
            console.log('Examining dataLayer entry:', index, event); // Simplified log
            
            if (event.event === 'confirmation') {
              console.log('Found confirmation event in dataLayer!');
              console.log('Transaction ID:', event.transactionId);
              console.log('Transaction Total:', event.transactionTotal);
              console.log('Products:', JSON.stringify(event.transactionProducts));
              console.log('Reference ID:', event.referenceId);
              console.log('User ID:', event.userId);
              
              // Log the full event for debugging
              console.log('Full transaction data:', JSON.stringify(event, null, 2));
              
              // Also log any available Google conversion cookies
              console.log('Google conversion cookies at purchase time:', getGoogleConversionCookies());
              
              sendPurchase(event);
            }
          });
        } else {
          console.log('No existing dataLayer events found, will monitor for new events');
        }
        
        // Override the dataLayer.push method to catch future events
        var originalPush = window.dataLayer.push;
        window.dataLayer.push = function() {
          // Call the original push method
          var result = originalPush.apply(window.dataLayer, arguments);
          
          // Log every dataLayer push for debugging
          console.log('dataLayer.push detected:', arguments[0]);
          
          // Check if the pushed data contains a confirmation event
          if (arguments[0] && arguments[0].event === 'confirmation') {
            console.log('CONFIRMATION EVENT CAPTURED!');
            console.log('Transaction ID:', arguments[0].transactionId);
            console.log('Transaction Total:', arguments[0].transactionTotal);
            console.log('Products:', JSON.stringify(arguments[0].transactionProducts));
            console.log('Reference ID:', arguments[0].referenceId);
            console.log('User ID:', arguments[0].userId);
            
            // Log the full event for debugging
            console.log('Full transaction data:', JSON.stringify(arguments[0], null, 2));
            
            // Also log any available Google conversion cookies
            console.log('Google conversion cookies at purchase time:', getGoogleConversionCookies());
            
            sendPurchase(arguments[0]);
          }
          
          return result;
        };
        
        console.log('DataLayer monitoring has been successfully set up');
      }
      
      // Initialize tracking
      function initialize() {
        try {
          console.log("Initializing Frndly tracking...");
          
          // Send initial page view (consent check removed, handled by sendEvent)
          sendEvent('page_view')
            .then(function(response) {
              console.log('Page view event sent successfully', response);
            })
            .catch(function(error) {
              console.error('Error sending page view event:', error);
            });
          
          // Set up enhanced measurement
          console.log("Setting up visibility tracking...");
          setupVisibilityTracking();
          
          console.log("Setting up click tracking...");
          setupClickTracking();
          
          console.log("Setting up form tracking...");
          setupFormTracking();
          
          // Handle page unload/navigation
          console.log("Setting up unload handler...");
          window.addEventListener('beforeunload', function() {
            // Calculate final engagement time
            if (window.performance) { // Consent check removed
              sendEvent('user_engagement', {
                engagement_time_msec: Math.round(performance.now())
              });
            }
          });
        
          // Monitor dataLayer for confirmation events
          console.log("Setting up dataLayer monitoring...");
          setupDataLayerMonitoring();
          
          console.log("Frndly tracking initialization complete");
        } catch (error) {
          console.error("Error during tracking initialization:", error);
        }
      }
      
      // Expose public API
      window.gtmServerClient = {
        sendEvent: sendEvent,
        sendPurchase: sendPurchase,
        initialize: initialize, // Expose initialize for manual triggering if needed
        hasConsentForTracking: hasConsentForTracking, // Expose consent checking function
        getGoogleConversionCookies: getGoogleConversionCookies // Expose cookie function for debugging
      };
      
      // Wait for DOM to be ready before initializing
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
        console.log("Waiting for DOMContentLoaded to initialize tracking");
      } else {
        // DOM is already ready
        console.log("DOM already loaded, initializing tracking immediately");
        initialize();
      }
      
      console.log("Frndly tracking script setup complete");
    })();
  