var wrapper = document.getElementById("resova-wrapper"),
    iframeSrc = "https://escapetheroomabq.resova.us?widget=true",
    guaActive = false,
    uaNumber = "UA-103155380-1",
    gtmId = "GTM-5CSCVZX",
    scrollingActive = "no";

function createResovaIframe(guaActive, uaNumber, gtmId, src) {
  var _ga = window[window.GoogleAnalyticsObject];

  if (((guaActive && uaNumber) || gtmId) && _ga) {
    try {
      var tracker = _ga.getAll()[0];
      var linker = new window.gaplugins.Linker(tracker);
      console.log("Linker is:", linker);
      if (linker)
        src = linker.decorate(src);
    } catch(err) {
      console.log("Error decorating URL:", err);
    }
  }

  console.log("iFrame SRC:", src);
  var wrapperHtml = "<iframe id=\"resova-iframe\" src=\"" + src + "\" style=\"width: 1px!important;min-width: 100%;*width: 100%; height: 100%; border: 0; transition: all 0.5s;\" scrolling=\"no\" onload=\"initResova()\" allow=\"payment\"></iframe>";
  wrapperHtml += '<div style="display:block!important;visibility:visible!important;opacity:1!important;z-index:9!important;overflow:visible!important;position:relative!important;top:auto!important;left:auto!important;float:none!important;width:100%!important;height:80px!important;line-height:1!important;margin:0!important;margin-top:-6px!important;padding:0!important;padding-bottom:30px!important;text-align:center!important;border:none!important;outline:none!important;background:#ffffff!important">    <a href="https://resova.com" target="_blank" style="display:inline-block!important;visibility:visible!important;opacity:1!important;z-index:9!important;overflow:visible!important;position:relative!important;top:auto!important;left:auto!important;float:none!important;width:auto!important;height:auto!important;line-height:1!important;margin:0!important;padding:0!important;text-align:center!important;text-decoration:none!important;font-size:0!important;vertical-align:middle!important;border:none!important;outline:none!important;">        <span style="display:block!important;visibility:visible!important;opacity:1!important;z-index:9!important;overflow:visible!important;position:relative!important;top:auto!important;left:auto!important;float:none!important;width:auto!important;height:10px!important;line-height:1!important;;margin:0!important;margin-right:7px!important;margin-bottom:10px!important;padding:0!important;font-size:11px!important;font-family:sans-serif!important;text-transform:uppercase!important;vertical-align:middle!important;border:none!important;outline:none!important;color:#4b5b67!important;">Escape Room Booking Software By</span>        <img src="https://d1ktc0bp273yrr.cloudfront.net/Universal/images/branding/resova_main_logos/resova_logo_main.svg" style="display:inline-block!important;visibility:visible!important;opacity:1!important;z-index:9!important;overflow:visible!important;position:relative!important;top:auto!important;left:auto!important;float:none!important;width:90px!important;height:26px!important;line-height:1!important;margin:0!important;padding:0!important;vertical-align:middle!important;border:none!important;outline:none!important;">    </a></div>';

  return wrapperHtml;
}

function startWidgetWhenGAReady() {
  const pollInterval = 100;
  const maxWaitTime = 1000;
  let elapsed = 0;
  let timeoutId = null;

  // Function to render iframe regardless of GA status
  const renderIframe = (decorated = false) => {
    try {
      console.log(decorated ? "GA is ready. Rendering iframe..." : "GA not ready. Rendering undecorated iframe.");
      wrapper.innerHTML = createResovaIframe(guaActive, uaNumber, gtmId, iframeSrc);
      wrapper.style.minHeight = '100px';
    } catch (err) {
      console.error("Error rendering iframe:", err);
      // Fallback rendering with minimal dependencies
      wrapper.innerHTML = "<iframe id=\"resova-iframe\" src=\"" + iframeSrc + "\" style=\"width: 1px!important;min-width: 100%;*width: 100%; height: 100%; border: 0;\" allow=\"payment\"></iframe>";
    }
  };

  const poll = () => {
    // Clear previous timeout to prevent memory leaks
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }

    try {
      const _ga = window[window.GoogleAnalyticsObject];
      const gaReady = _ga && 
                      typeof _ga.getAll === 'function' && 
                      _ga.getAll() && 
                      window.gaplugins && 
                      typeof window.gaplugins.Linker === 'function';

      if (gaReady) {
        renderIframe(true);
        return; // Exit polling
      } 
    } catch (err) {
      console.warn("Error checking GA status:", err);
      // Continue to timeout check
    }
    
    // Check if we've exceeded max wait time
    if (elapsed >= maxWaitTime) {
      renderIframe(false);
      return; // Exit polling
    }
    
    // Continue polling
    elapsed += pollInterval;
    timeoutId = setTimeout(poll, pollInterval);
  };

  // Start polling
  poll();
}

// ---- Existing Logic for Resova Message Handling ---- //

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";

eventer(messageEvent, function(e) {
  try {
    if (IsJsonString(e.data)) {
      var obj = JSON.parse(e.data);
      if (obj["readjust_height"] !== undefined)
        AdjustIframeHeightOnLoad(obj["readjust_height"]);
      if (obj["scroll_top"] !== undefined) {
        var resovaScrollTop = findPosY(document.getElementById("resova-wrapper"));
        window.scrollTo(0, resovaScrollTop - 30);
      }
      if (obj["gtag_event"] !== undefined) {
        dataLayerEvents.push(obj["gtag_event"]);
        if (gtmReady) {
          try {
            for (var event of dataLayerEvents) {
              console.log("dataLayerEvents", event);
              window.dataLayer = window.dataLayer || [];
              window.dataLayer.push(event);
            }
            dataLayerEvents = [];
          } catch (err) {
            console.error("Error processing GTM events:", err);
          }
        }
      }
    }
  } catch (err) {
    console.error("Error handling message event:", err);
  }
}, false);

function initResova() {
  try {
    var iframe = document.getElementById("resova-iframe");
    if (iframe) {
      iframe.style.backgroundColor = "transparent";
    }
    document.addEventListener('touchstart', {}); // iOS interaction
  } catch (err) {
    console.error("Error in initResova:", err);
  }
}

function AdjustIframeHeightOnLoad(height) {
  try {
    const iframe = document.getElementById("resova-iframe");
    if (iframe) {
      iframe.style.backgroundColor = "transparent";
      iframe.style.height = height + 'px';
    }
  } catch (err) {
    console.error("Error adjusting iframe height:", err);
  }
}

function IsJsonString(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

function findPosY(obj) {
  var curtop = 0;
  try {
    if (obj) {
      if (obj.offsetParent) {
        while (obj.offsetParent) {
          curtop += obj.offsetTop;
          obj = obj.offsetParent;
        }
      } else if (obj.y) {
        curtop += obj.y;
      }
    }
  } catch (err) {
    console.error("Error finding position Y:", err);
  }
  return curtop;
}

// ---- Google Tag Manager Init ---- //
var gtmReady = false;
var dataLayerEvents = [];

function initializeGtag() {
  try {
    window.dataLayer = window.dataLayer || [];
    window.gtag = function () {
      window.dataLayer.push(arguments);
    };
    gtmReady = true;
    
    // Process any queued events
    if (dataLayerEvents.length > 0) {
      for (var event of dataLayerEvents) {
        console.log("Processing queued event:", event);
        window.dataLayer.push(event);
      }
      dataLayerEvents = [];
    }
  } catch (err) {
    console.error("Error initializing gtag:", err);
    gtmReady = true; // Set to true anyway to prevent events from being stuck
  }
}

function checkGtagLoaded() {
  var pollInterval = 200;
  var maxWaitTime = 1000;
  var elapsedTime = 0;
  var timeoutId = null;

  var poll = function() {
    // Clear previous timeout to prevent memory leaks
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
    
    try {
      if (
        window.google_tag_manager &&
        window.google_tag_manager.dataLayer &&
        window.google_tag_manager.dataLayer.gtmDom
      ) {
        initializeGtag();
        return; // Exit polling
      }
    } catch (err) {
      console.warn("Error checking GTM status:", err);
      // Continue to timeout check
    }

    // Check if we've exceeded max wait time
    if (elapsedTime >= maxWaitTime) {
      console.warn("GTM not loaded within timeout. Some tracking features may not work.");
      // Set gtmReady to true anyway to prevent events from being stuck in queue forever
      gtmReady = true;
      return; // Exit polling
    }

    // Continue polling
    elapsedTime += pollInterval;
    timeoutId = setTimeout(poll, pollInterval);
  };

  // Start polling
  poll();
}

// Start the processes
startWidgetWhenGAReady();
checkGtagLoaded();