(function() {
  'use strict';
  // User experience analytics with Beacon API
  var analyticsUrl = 'https://i.searchhelp.in/track/browser';
  var sessionId = 's2EMcg6WGdtgPjU5K1Bf2D3XMPFQqhX5';
  var pageLoadTime = Date.now();
  var unloadCaptured = false;
  var consentState = 'not_required';
  
  function captureEvent(eventType, eventData) {
    var payload = JSON.stringify({
      eventType: eventType,
      sessionId: sessionId,
      pageUrl: window.location.href,
      pageTitle: document.title,
      referrer: document.referrer,
      timestamp: new Date().toISOString(),
      viewportWidth: window.innerWidth,
      viewportHeight: window.innerHeight,
      screenWidth: screen.width,
      screenHeight: screen.height,
      eventData: Object.assign({ consentState: consentState }, eventData || {})
    });
    
    // Use text/plain to avoid CORS preflight - server will parse as JSON
    if (navigator.sendBeacon) {
      var blob = new Blob([payload], { type: 'text/plain' });
      navigator.sendBeacon(analyticsUrl, blob);
    } else {
      fetch(analyticsUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'text/plain' },
        body: payload,
        keepalive: true
      }).catch(function() {});
    }
  }
  
  function captureSessionEnd() {
    if (!unloadCaptured) {
      unloadCaptured = true;
      captureEvent('page.unload', {
        timeOnPage: Date.now() - pageLoadTime,
        pageType: 'related'
      });
    }
  }
  
  // Capture page view — deferred for EU users until consent is established
  captureEvent('page.view', { pageType: 'related' });

  // Capture session end with multiple fallbacks (prevent duplicates)
  document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
      captureSessionEnd();
    }
  });
  
  window.addEventListener('pagehide', function() {
    captureSessionEnd();
  });

  // EU detection (server-injected)
  var isEuUser = false;
  
  // Callback function for when related searches are loaded
  window.afsRelatedSearchLoadedCallback = function(containerName, adsLoaded, isExperimentVariant, callbackOptions) {
    if (/[?&]afsdebug=1/.test(window.location.search)) {
      console.log('AFS Related Search Loaded:', {
        containerName: containerName,
        adsLoaded: adsLoaded,
        isExperimentVariant: isExperimentVariant,
        callbackOptions: callbackOptions,
        termPositions: callbackOptions ? callbackOptions.termPositions : null
      });
    }
    
    if (adsLoaded) captureEvent('related.loaded', { containerName: containerName, adsLoaded: adsLoaded, isExperimentVariant: isExperimentVariant, callbackOptions: callbackOptions });
  };
  
  var pageOptions = {
  "pubId": "pub-9965597650604164",
  "styleId": "9932590299",
  "relatedSearchTargeting": "content",
  "hl": "en",
  "referrerAdCreative": "identifyforce.com",
  "resultsPageBaseUrl": "https://searchhelp.in/search/?fi=0&gp_session=s2EMcg6WGdtgPjU5K1Bf2D3XMPFQqhX5&rso=content",
  "resultsPageQueryParam": "s",
  "ignoredPageParams": "sid,rs,rs2,url,pageTitle,pageReferrer,screenInfo,fi,cid,rac,sub,utm_source,hide_featured,d,display,dp,edid,rsoc,ts,utm_medium,utm_campaign,utm_term,utm_content,gclid,dclid,fbclid,msclkid,gp,gp_session,rso,session_id,sessionid,ref,referrer,source",
  "adsafe": "low",
  "ivt": false,
  "clicktrackUrl": "https://i.searchhelp.in/track/click?session=s2EMcg6WGdtgPjU5K1Bf2D3XMPFQqhX5&eventType=INTERACTION_QUERY&site=3e67d602-1ffd-4166-87c3-4814a9147014&campaign=3c4ac6a6-e084-40ba-8d49-57498b22786e&sub=identifyforce.com"
};
  var rsblock1 = {
  "container": "afscontainer1",
  "relatedSearches": 6
};
  var rsblock2 = {
  "container": "rs_eoc",
  "relatedSearches": 8
};
  
  // Add callback function reference to rsblock1
  rsblock1.adLoadedCallback = afsRelatedSearchLoadedCallback;
  
  // Add callback function reference to rsblock2
  rsblock2.adLoadedCallback = afsRelatedSearchLoadedCallback;
  
  function initAFS() {
    debugLog('[AFS:1] initAFS() entered');
    var googCsaInvoked = false;
    var consentResolved = false;
    var afsDebug = /[?&]afsdebug=1/.test(window.location.search);

    function debugLog() { if (afsDebug) { console.log.apply(console, arguments); } }
    function debugWarn() { if (afsDebug) { console.warn.apply(console, arguments); } }
    function setConsentState(state) {
      if (isEuUser && typeof consentState !== 'undefined') { consentState = state; }
    }

    function callCsa() {
      debugLog('[AFS:6] callCsa() entered — typeof _googCsa:', typeof _googCsa);
      if (isEuUser && typeof captureEvent === 'function') {
        captureEvent('page.view', { pageType: 'related' });
      }
      _googCsa('relatedsearch', pageOptions, rsblock1, rsblock2);
    }
    function doInvoke(state) {
      if (googCsaInvoked) return;
      googCsaInvoked = true;
      setConsentState(state);
      debugLog('[AFS:4] doInvoke() — calling _googCsa directly');
      callCsa();
    }
    function doInvokeWithReload(state) {
      if (googCsaInvoked) return;
      googCsaInvoked = true;
      setConsentState(state);
      debugLog('[AFS:5] doInvokeWithReload() — creating fresh ads.js script tag');
      var adsScript = document.createElement('script');
      adsScript.async = true;
      adsScript.src = 'https://www.google.com/adsense/search/ads.js';
      adsScript.onload = function() {
        debugLog('[AFS:5b] fresh ads.js onload fired — typeof _googCsa:', typeof _googCsa);
        callCsa();
      };
      adsScript.onerror = function() {
        debugLog('[AFS:5e] fresh ads.js FAILED to load');
        if (typeof _googCsa !== 'undefined') { callCsa(); }
      };
      document.head.appendChild(adsScript);
    }
    if (isEuUser && false) {
      var tcfPollCount = 0;
      // Hard deadline: if no qualifying consent event resolves within the poll
      // budget (8s) + a small buffer, invoke anyway (Google serves limited ads
      // where eligible) rather than leaving zero fill.
      var hardDeadline = setTimeout(function() {
        if (consentResolved) return;
        consentResolved = true;
        debugWarn('[AFS:2c] consent deadline reached — invoking anyway (limited fill)');
        doInvoke('limited');
      }, 8500);
      debugLog('[AFS:2] isEuUser:true — waiting for TCF consent');

      function onConsentResolved() {
        if (consentResolved) return;
        consentResolved = true;
        clearTimeout(hardDeadline);
      }

      function pollForTcf() {
        if (typeof window.__tcfapi !== 'undefined') {
          debugLog('[AFS:2] __tcfapi found after', tcfPollCount, 'polls (~' + (tcfPollCount * 100) + 'ms)');
          window.__tcfapi('addEventListener', 2, function(tcData, success) {
            debugLog('[AFS:3] TCF callback — eventStatus:', tcData && tcData.eventStatus, '— gdprApplies:', tcData && tcData.gdprApplies, '— success:', success);
            if (success && tcData && tcData.gdprApplies === false) {
              onConsentResolved();
              doInvoke('not_required');
              return;
            }
            if (success && (tcData.eventStatus === 'tcloaded' || tcData.eventStatus === 'useractioncomplete')) {
              window.__tcfapi('removeEventListener', 2, function() {}, tcData.listenerId);
              onConsentResolved();
              if (tcData.eventStatus === 'useractioncomplete') {
                debugLog('[AFS:4] useractioncomplete — calling doInvokeWithReload');
                doInvokeWithReload('granted');
              } else {
                debugLog('[AFS:4] tcloaded — calling doInvoke directly');
                doInvoke('granted');
              }
            }
          });
        } else if (tcfPollCount < 80) {
          tcfPollCount++;
          setTimeout(pollForTcf, 100);
        } else {
          onConsentResolved();
          debugWarn('[AFS:2b] __tcfapi absent — invoking directly (limited fill)');
          doInvoke('limited');
        }
      }
      pollForTcf();
    } else {
      debugLog('[AFS:2b] bypassing TCF (non-EU, related/RSOC, or CMP disabled) — calling doInvoke directly');
      doInvoke(isEuUser ? 'limited' : 'not_required');
    }
  }

  // Load Google AFS library if not already loaded
  if (typeof _googCsa === 'undefined') {
    var script = document.createElement('script');
    script.async = true;
    script.src = 'https://www.google.com/adsense/search/ads.js';
    script.onload = initAFS;
    script.onerror = function() { console.error('AFS: Failed to load ads.js'); };
    document.head.appendChild(script);
  } else {
    initAFS();
  }
})();