if (!window.__DEBUG_MODE_LOADED__) {
  window.__DEBUG_MODE_LOADED__ = true;

  var DEBUG_MODE = false;

  var debugLog = (...args) => {
    if (DEBUG_MODE) {
      console.log('[FRONTROW]', ...args);
    }
  };

  function frDebounce(func, timeout){
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => { func.apply(this, args); }, timeout);
    };
  }
}

var div = document.querySelector("div#frontrow-portal")

if(!div) {
  div = document.createElement("div")
  div.id = "frontrow-portal"
}

var frontrowModalUrl = "https://app.thefrontrowhealth.com/api/widgets/modal?presentation_type=brand&amp;product_id=2377"

function setupIframe(className, url, zIndex = 99999997) {
  if (document.querySelector("." + className) === null) {
    const frModalIframe = document.createElement("iframe")
    frModalIframe.classList.add("iframe")
    frModalIframe.classList.add("frontrow")
    frModalIframe.classList.add(className)
    frModalIframe.src = url.replaceAll("&amp;", "&")
    frModalIframe.style.borderStyle = "none"
    frModalIframe.style.zIndex = zIndex
    div.appendChild(frModalIframe)
  }
}

function setupGptIframe(className, url, zIndex = 99999997) {
  if (document.querySelector("." + className) === null) {
    const frModalIframe = document.createElement("iframe")
    frModalIframe.classList.add(className)
    frModalIframe.id = className;
    frModalIframe.src = url.replaceAll("&amp;", "&")
    frModalIframe.style.zIndex = zIndex
    div.appendChild(frModalIframe)
  }
}

setupIframe("iframe-modal-frontrow-2377", frontrowModalUrl, 99999998)

var providerProfileUrl = "https://app.thefrontrowhealth.com/api/widgets/v1/provider_profiles?widget_id=3118"
setupIframe("iframe-provider-profile-modal", providerProfileUrl, 99999999)

document.body.appendChild(div)

function openFrModal(presentation_type) {
  debugLog('OPENING_FRONTROW_MODAL');
  const frModalIframe = document.querySelector("iframe.iframe-modal-frontrow-2377");
  frModalIframe.contentWindow.postMessage({ name: "UPDATE_UTM_PARAMS", utm_content: presentation_type }, "*");
  frModalIframe.style.display = "block";
  frModalIframe.contentWindow.focus()
}

function setupAndOpenProviderModal(data, presentation_type = "badge") {
  const ifm = document.querySelector('.iframe-provider-profile-modal');
  ifm.contentWindow.postMessage({ name: "UPDATE_UTM_PARAMS", utm_content: presentation_type }, "*");
  ifm.contentWindow.postMessage({name: "OPEN", data}, "*");
  ifm.style.display = "block"
  ifm.contentWindow.focus();
}

function closeOriginModal(origin) {
  const iframes = [...document.querySelectorAll("iframe")]
  const frModalIframe = iframes.find(i => i.contentWindow === origin)

  popFocus()
  frModalIframe.style.display = "none"
}

function closeAllModals() {
  const allModals = [...document.querySelectorAll(".iframe.frontrow")]

  resetFocus()

  allModals.forEach(m => {
    m.style.display = "none"
  })
}

if(typeof FOCUS_STACK == 'undefined') {
  FOCUS_STACK = [];
}

function focusLastOrigin(origin) {
  if(!origin) return;

  const iframes = [...document.querySelectorAll("iframe")]
  const frModalIframe = iframes.find(i => i.contentWindow === origin)

  frModalIframe?.contentWindow?.focus?.()
}

function resetFocus() {
  focusLastOrigin(FOCUS_STACK[0]);
  FOCUS_STACK = []
}

function popFocus() {
  focusLastOrigin(FOCUS_STACK.pop())
}


function setupStyles(styles) {
  var frStyleSheet = document.createElement("style");
  frStyleSheet.textContent = styles;
  document.head.appendChild(frStyleSheet);
}

// Load shared token utilities
// Generate UUID helper
if (!window.generateUUID) {
  window.generateUUID = function() {
    if (crypto && crypto.randomUUID) {
      return crypto.randomUUID();
    } else if (crypto && crypto.getRandomValues) {
      const array = new Uint8Array(16);
      crypto.getRandomValues(array);
      array[6] = (array[6] & 0x0f) | 0x40;
      array[8] = (array[8] & 0x3f) | 0x80;
      return Array.from(array, (b, i) => {
        const hex = b.toString(16).padStart(2, '0');
        return [4, 6, 8, 10].includes(i) ? '-' + hex : hex;
      }).join('');
    } else {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    }
  };
}

// Generate or retrieve visitor token (persists across sessions)
if (!window.getOrCreateVisitorToken) {
  window.getOrCreateVisitorToken = function() {
    let token = localStorage.getItem('frontrow_visitor_token');
    if (!token) {
      token = window.generateUUID();
      localStorage.setItem('frontrow_visitor_token', token);
    }
    return token;
  };
}

// Generate or retrieve visit token (persists for current session only)
if (!window.getOrCreateVisitToken) {
  window.getOrCreateVisitToken = function() {
    let token = sessionStorage.getItem('frontrow_visit_token');
    if (!token) {
      token = window.generateUUID();
      sessionStorage.setItem('frontrow_visit_token', token);
    }
    return token;
  };
}


// Store tokens globally to avoid redeclaration errors
if (typeof window.VISITOR_TOKEN === 'undefined') {
  window.VISITOR_TOKEN = window.getOrCreateVisitorToken();
}
if (typeof window.VISIT_TOKEN === 'undefined') {
  window.VISIT_TOKEN = window.getOrCreateVisitToken();
}




var frBrandStyles = `
  #iframe-frontrow-brand {
    display: none;
  }

  #frontrow-sticky-regular {
    height: 62px !important;
    width: 100%;
    display: none;
  }

  .iframe.frontrow {
    display: none;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 99999997;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  

`

setupStyles(frBrandStyles);

function resizeHeight(value, origin) {
  debugLog('RESIZING_HEIGHT:', { value, origin });
  const iframes = [...document.querySelectorAll("iframe.iframe-frontrow")]
  const badgeIframe = iframes.find(i => i.contentWindow === origin)

  if (badgeIframe) {
    badgeIframe.style.height = value + "px";
    badgeIframe.style.display = "block";
    debugLog('BADGE_IFRAME_RESIZED:', { id: badgeIframe.id, newHeight: value });
  }

}

try {
  window.addEventListener("message", ev => {

    if((ev.data?.name?.includes && ev.data?.name?.includes("OPEN")) || (ev.data?.includes && ev.data?.includes("OPEN"))) FOCUS_STACK.push(ev.source);

    if(ev.data === "OPEN_MODAL") return openFrModal("badge");
    if(ev.data === "CLOSE_ALL_MODALS") return closeAllModals();
    if(ev.data === "CLOSE_STICKY") return closeSticky();
    if(ev.data.includes && ev.data.includes("CLOSE")) return closeOriginModal(ev.source);
    if(ev.data?.name === "RESIZE_HEIGHT") return resizeHeight(ev.data?.value, ev.source);
    if(ev.data?.name === "OPEN_PROVIDER_MODAL") return setupAndOpenProviderModal(ev.data.data);
    if(ev.data?.name === "BRAND_REQUEST_READY_STATUS") {
      debugLog('SENDING_READY_STATUS');
      ev.source.postMessage({ name: "PARENT_READY" }, "*");
      return;
    }
  });

  function sendReadyToBrandIframes() {
    const iframe = document.querySelector("#iframe-frontrow-brand") || document.querySelector("#iframe-frontrow-homepage");
    if (iframe) {
      try {
        iframe.contentWindow.postMessage({ name: "PARENT_READY" }, "*");
      } catch (e) {
        debugLog('ERROR_SENDING_READY_SIGNAL:', e);
      }
    }
  }

  sendReadyToBrandIframes();
  debugLog('PARENT_READY_STATE_SET');
} catch (error) {
  debugLog('ERROR_SETTING_UP_MESSAGE_LISTENER:', error);
}

function trackView3118() {
  let VIEW_WIDGET = false
  function trackWidgetView() {
    if (!VIEW_WIDGET) {
      frTrack("view_widget")
      VIEW_WIDGET = true
    }
  }

  function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return ((rect.top > 0 && rect.top < innerHeight) ||
            (rect.bottom > 0 && rect.bottom < innerHeight)) &&
        ((rect.left > 0 && rect.left < innerWidth) || (rect.right > 0 && rect.right < innerWidth));
  }

  function getSafeUrl() {
    try {
      return window?.parent?.location?.href || window?.location?.href || '';
    } catch (e) {
      return '';
    }
  }

  function frTrack(event, opts = {}) {
    try {
      // Get or create tokens - read from storage first, fallback to parent's utility functions if needed
      const visitorToken = localStorage.getItem('frontrow_visitor_token');
      const visitToken = sessionStorage.getItem('frontrow_visit_token');

      fetch("https://app.thefrontrowhealth.com/api/tracking", {
        method: "POST",
        body: JSON.stringify({
          event,
          visitor_token: visitorToken,
          visit_token: visitToken,
          opts: {
            ...opts,
            healthBrandProductId: 2377,
            presentationType: 'brand',
            url: getSafeUrl(),
            version: '8',
            is_sticky: false
          }
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      }).catch(() => {});
    } catch (e) {
      console.error('Error tracking:', e);
    }
  }

  function findElement() {
    try {
      const element = document.querySelector('.iframe-frontrow-homepage');
      if (element) return element;

      const fallbackElement = document.querySelector('#iframe-frontrow-brand');
      if (fallbackElement) return fallbackElement;

      return null;
    } catch (e) {
      debugLog('ERROR_FINDING_ELEMENT:', e);
      return null;
    }
  }

  function checkVisibility() {
    try {
      const element = findElement();
      if (element && isInViewport(element)) {
        trackWidgetView();
        window.removeEventListener('scroll', checkVisibility);
        window.removeEventListener('resize', checkVisibility);
      }
    } catch (e) {
      debugLog('ERROR_CHECKING_VISIBILITY:', e);
    }
  }

  window.addEventListener('scroll', checkVisibility);
  window.addEventListener('resize', checkVisibility);
}

try {
  trackView3118();
} catch (e) {
  debugLog('ERROR_TRACKING_VIEW_QUANT:', e);
}

