window.DigitalFeedback['https://cdn.us2.hxplatform.com/loader/prod/scenario?programKey=T3xr60&scenarioId=75&programVersion=96'] = function (api) {
//Conversion
let triggered = false;

// SPA initialization guard
if (window.conversionInitialized) {
  return;
}

window.conversionInitialized = true;

// Excluded URL Check
const excludedUrls = ["checkout", "cart"];
const testURL = ["google"];

// ----------------------------------------
// URL / SPA Helpers
// ----------------------------------------

function getCurrentUrl() {
  return window.location.href;
}

function isExcludedUrl() {
  const currentUrl = getCurrentUrl().toLowerCase();

  return excludedUrls.some((path) => currentUrl.includes(path));
}

function isTestUrl() {
  const currentUrl = getCurrentUrl().toLowerCase();

  return testURL.some((path) => currentUrl.includes(path));
}

// ----------------------------------------
// Test Mode
// ----------------------------------------

if (new URLSearchParams(window.location.search).has("ditest")) {
  console.log("setting test showPercent.....");
  sessionStorage.showPercent = "1";
}

if (sessionStorage.showPercent !== "1") {
  //console.log("showPercent broken...");
  return;
}

if (getCookie("T3xr60")) {
  //console.log("FATIGUE FOUND NO INTERCEPT WILL TRIGGER");
} else {
  if (sessionStorage.showPercent == "1") {
    //console.log("WILL TRIGGER CONVERSION");
  }
}

// ----------------------------------------
// Data Object
// ----------------------------------------

let dObj = {
  url: window.location.href,
  browser: null,
  os: null,
  deviceType: null,
  pg_visits: null,
  paid_social: 0,
};

// Set Paid Social
function updatePaidSocial() {
  const params = new URLSearchParams(window.location.search);

  dObj.paid_social = params.get("camp") === "PDSOC" ? 1 : 0;
}

// Update URL-dependent dObj values
function updateUrlData() {
  dObj.url = getCurrentUrl();
  updatePaidSocial();
}

// ----------------------------------------
// Browser / Device Parameters
// ----------------------------------------

function getParams() {
  // --- Screen size ---
  dObj.screenSize = window.screen.width + "x" + window.screen.height;

  // --- Device type ---
  const ua = navigator.userAgent;

  const isMobile = /Mobi|Android/i.test(ua);

  const isTablet = /Tablet|iPad/i.test(ua);

  dObj.deviceType = isTablet ? "tablet" : isMobile ? "mobile" : "desktop";

  // --- Browser + version ---
  if (/Chrome\/(\d+)/.test(ua) && !/Edg/.test(ua)) {
    dObj.browser = "Chrome";
  } else if (/Edg\/(\d+)/.test(ua)) {
    dObj.browser = "Edge";
  } else if (/Firefox\/(\d+)/.test(ua)) {
    dObj.browser = "Firefox";
  } else if (/Version\/(\d+).+Safari/.test(ua)) {
    dObj.browser = "Safari";
  }

  // --- OS + version ---
  if (/Windows NT/.test(ua)) {
    dObj.os = "Windows";
  } else if (/Mac OS X/.test(ua)) {
    dObj.os = "macOS";
  } else if (/Android/.test(ua)) {
    dObj.os = "Android";
  } else if (/iPhone|iPad/.test(ua)) {
    dObj.os = "iOS";
  }

  //console.log(dObj);
}

getParams();
updateUrlData();

// ----------------------------------------
// Active Timer
// ----------------------------------------

function getTimerState() {
  return (
    JSON.parse(sessionStorage.getItem("activeTimer")) || {
      startTime: Date.now(),
      lastStart: Date.now(),
      accumulated: 0,
      isActive: true,
    }
  );
}

function setTimerState(state) {
  sessionStorage.setItem("activeTimer", JSON.stringify(state));
}

// Initialize timer if it doesn't exist
if (!sessionStorage.getItem("activeTimer")) {
  setTimerState({
    startTime: Date.now(),
    lastStart: Date.now(),
    accumulated: 0,
    isActive: true,
  });

  //console.log("Timer initialized");
}

function resumeTimer() {
  const state = getTimerState();

  if (!state.isActive) {
    state.lastStart = Date.now();
    state.isActive = true;

    setTimerState(state);
  }
}

function pauseTimer() {
  const state = getTimerState();

  if (state.isActive && state.lastStart) {
    const now = Date.now();

    state.accumulated += now - state.lastStart;

    state.lastStart = null;
    state.isActive = false;

    setTimerState(state);
  }
}

function getActiveTime() {
  const state = getTimerState();

  if (state.isActive && state.lastStart) {
    return state.accumulated + (Date.now() - state.lastStart);
  }

  return state.accumulated;
}

function ensureTimerRunning() {
  const state = getTimerState();

  if (!state.isActive || !state.lastStart) {
    state.lastStart = Date.now();
    state.isActive = true;

    setTimerState(state);
  }
}

ensureTimerRunning();

// ----------------------------------------
// Visibility / Page Lifecycle
// ----------------------------------------

document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    pauseTimer();
  } else {
    resumeTimer();
  }
});

window.addEventListener("pagehide", pauseTimer);

// ----------------------------------------
// Timer Check
// ----------------------------------------

let timerInterval = null;

function startTimerCheck() {
  if (isTestUrl()) {
    sessionStorage.testExit = "1";

    if (screen.width <= 768) {
      enableMobileExitIntent();
    } else {
      enableExitIntent();
    }

    return;
  }

  timerInterval = setInterval(() => {
    const activeSeconds = Math.round(getActiveTime() / 1000);

    //console.log(activeSeconds);

    // Mobile: 90 seconds
    if (screen.width <= 768 && activeSeconds >= 90 && !isExcludedUrl()) {
      clearInterval(timerInterval);
      timerInterval = null;

      enableMobileExitIntent();

      return;
    }

    // Desktop: 120 seconds
    if (activeSeconds >= 120 && !isExcludedUrl()) {
      clearInterval(timerInterval);
      timerInterval = null;

      if (screen.width > 768) {
        enableExitIntent();
      }

      return;
    }
  }, 1000);
}

// ----------------------------------------
// Same Day / 45-Day Fatigue
// ----------------------------------------

function setCookie(name, value, options) {
  let parts = [encodeURIComponent(name) + "=" + encodeURIComponent(value)];

  if (options) {
    if ("expiry" in options && typeof options.expiry === "number") {
      // Treat expiry as days instead of seconds
      const expiryDate = new Date(+new Date() + options.expiry * 86400000);

      parts.push("expires=" + expiryDate.toGMTString());
    }

    if ("domain" in options) {
      parts.push("domain=" + options.domain);
    }

    if ("path" in options) {
      parts.push("path=" + options.path);
    }

    if ("secure" in options && options.secure) {
      parts.push("secure");
    }

    if ("samesite" in options) {
      parts.push("SameSite=" + options.samesite);
    }
  }

  document.cookie = parts.join("; ");
}

function getCookie(name, all) {
  const matches = [];

  const cookies = document.cookie.split(/; */);

  for (let i = 0; i < cookies.length; i++) {
    const parts = cookies[i].split("=");

    if (parts[0] === encodeURIComponent(name)) {
      matches.push(decodeURIComponent(parts[1].replace(/\+/g, "%20")));
    }
  }

  return all ? matches : matches[0];
}

// ----------------------------------------
// Desktop Exit Intent
// ----------------------------------------

function enableExitIntent() {
  //console.log("Desktop exit intent active");

  const validShowPercents = ["1"];

  function onMouseLeave(e) {
    triggered = sessionStorage.getItem("dfTriggered") === "true";

    if (!sessionStorage.testExit) {
      if (
        triggered ||
        getCookie("T3xr60") ||
        !validShowPercents.includes(sessionStorage.showPercent)
      ) {
        return;
      }
    }

    // Re-check the current SPA URL
    if (isExcludedUrl()) {
      return;
    }

    if (e.clientY <= 20) {
      // Update URL/dObj immediately before
      // displaying the survey.
      updateUrlData();

      //console.log("Conversion Triggered");

      sessionStorage.setItem("dfTriggered", "true");

      api().data(dObj).container("Modal").survey("p154428696932").show();

      sessionStorage.setItem("T3xr60", "1");

      setCookie("T3xr60", "1", {
        path: "/",
        expiry: 45,
        secure: true,
        samesite: "None",
      });

      triggered = true;

      document.body.removeEventListener("mouseleave", onMouseLeave);
    }
  }

  document.body.addEventListener("mouseleave", onMouseLeave);
}

// ----------------------------------------
// Mobile Exit Intent
// ----------------------------------------

function enableMobileExitIntent() {
  //console.log(
  //  "90s reached — Mobile exit intent active"
  //);

  const validShowPercents = ["1"];

  let lastScrollTop = window.pageYOffset || document.documentElement.scrollTop;

  let lastTime = Date.now();

  function onScroll() {
    let triggered = sessionStorage.getItem("dfTriggered") === "true";

    if (!sessionStorage.testExit) {
      if (
        triggered ||
        getCookie("T3xr60") ||
        !validShowPercents.includes(String(sessionStorage.showPercent))
      ) {
        window.removeEventListener("scroll", onScroll);

        return;
      }
    }

    // Re-check the current SPA URL
    if (isExcludedUrl()) {
      return;
    }

    const currentScrollTop =
      window.pageYOffset || document.documentElement.scrollTop;

    const currentTime = Date.now();

    const distance = lastScrollTop - currentScrollTop;

    const timeElapsed = (currentTime - lastTime) / 1000;

    if (timeElapsed > 0.05) {
      const speed = distance / timeElapsed;

      if (distance > 10 && speed >= 160) {
        // Update URL/dObj immediately before
        // displaying the survey.
        updateUrlData();

        sessionStorage.setItem("dfTriggered", "true");

        sessionStorage.setItem("T3xr60", "1");

        setCookie("T3xr60", "1", {
          path: "/",
          expiry: 45,
          secure: true,
          samesite: "None",
        });

        api().data(dObj).container("Modal").survey("p154428696932").show();

        triggered = true;

        window.removeEventListener("scroll", onScroll);
      }
    }

    lastScrollTop = currentScrollTop;

    lastTime = currentTime;
  }

  window.addEventListener("scroll", onScroll);
}

// ----------------------------------------
// Track Page Visits
// ----------------------------------------

function trackPageVisit(urlOverride) {
  const currentUrl = (urlOverride || window.location.href).toLowerCase();

  // Retrieve existing data from sessionStorage
  let trackingData = JSON.parse(sessionStorage.getItem("pageTracking")) || {
    visitedPages: [],
    uniquePages: {},
    totalPageCount: 0,
  };

  // Update total pages visited
  trackingData.totalPageCount += 1;

  // Update page_visits
  dObj.pg_visits = trackingData.totalPageCount;

  // Update the list of visited pages
  trackingData.visitedPages.push(currentUrl);

  // Update unique page visits
  if (!trackingData.uniquePages[currentUrl]) {
    trackingData.uniquePages[currentUrl] = true;
  }

  // Save updated data
  sessionStorage.setItem("pageTracking", JSON.stringify(trackingData));
}

// ----------------------------------------
// SPA Navigation Tracking
// ----------------------------------------

let lastTrackedUrl = window.location.href;

function handleSpaNavigation() {
  const currentUrl = window.location.href;

  // Don't count the same URL twice
  if (currentUrl === lastTrackedUrl) {
    return;
  }

  lastTrackedUrl = currentUrl;

  // Update URL-dependent data
  updateUrlData();

  // Track the SPA route as a page visit
  trackPageVisit(currentUrl);

  //console.log(
  //  "SPA navigation:",
  //  currentUrl
  //);
}

// Browser back / forward
window.addEventListener("popstate", handleSpaNavigation);

// Capture history.pushState
const originalPushState = history.pushState;

history.pushState = function () {
  const result = originalPushState.apply(this, arguments);

  handleSpaNavigation();

  return result;
};

// Capture history.replaceState
const originalReplaceState = history.replaceState;

history.replaceState = function () {
  const result = originalReplaceState.apply(this, arguments);

  handleSpaNavigation();

  return result;
};

// ----------------------------------------
// Initial Setup
// ----------------------------------------

if (triggered === false) {
  startTimerCheck();

  // Track initial page
  trackPageVisit();

  //console.log("starting timer");
}

};