let env = "https://chat.rippey.ai/index.html";
const isProduction = "true";
// setTimeout(() => { frameInit(); }, 5000);
let checkInterval = setInterval(checkIfDOMLoaded, 2000);

// const __original_console_log = console.log;
// console.log = function (...args) {
//   if (console.enable === true) {
//     // ability to manually enable console log if needed
//     __original_console_log.apply(this, args);
//   }
// }
function checkIfDOMLoaded() {
  if (document.readyState === "complete") {
    console.log("Running through document ready state");
    const isSuccess = frameInit();
    if (isSuccess) clearInterval(checkInterval);
  } else {
    window.onload = () => {
      console.log("Running through onload event");
      const isSuccess = frameInit();
      if (isSuccess) clearInterval(checkInterval);
    };
  }
}

function frameInit() {

  try {
    const iframeExists = document.getElementById("rippeybot");

    if(iframeExists) {
      console.log("Iframe already exists. Skipping initialization.");
     return;
    }

    let envPath = env;
    let hostname = window.location.hostname;
    if (isProduction === "false") {
      hostname = window.location.pathname.split("/").pop();
    }
    const queryInfo = {
      userId: getUserId(),
      userOrigin: hostname
    };

    envPath += "?token=" + btoa(JSON.stringify(queryInfo));

    let bodyTag = document.body;
    let iframeTag = document.createElement("iframe");
    iframeTag.id = "rippeybot";
    iframeTag.src = envPath;
    iframeTag.style.margin = "0";
    iframeTag.style.bottom = "0px";
    iframeTag.style.right = "0px";
    iframeTag.style.width = "360px";
    iframeTag.style.height = "140px";
    iframeTag.style.position = "fixed";
    iframeTag.style.zIndex = "99999999999";
    iframeTag.style.border = "none";
    iframeTag.style.overflow = "hidden";
    iframeTag.crossOrigin = "";

    window.addEventListener("message", event => {
      let sy = event.data;
      if (sy && sy.chatStyle) {
        iframeTag.style.height = sy.chatStyle.height;
        iframeTag.style.width = sy.chatStyle.width;
      }

      if (sy && sy.userId) {
        localStorage.setItem("user_id", sy.userId);
      }
    });

    // only return true in case of successful body append
    if (bodyTag) {
      bodyTag.appendChild(iframeTag);
      return true;
    }
    return false;
  } catch (e) {
    return false;
  }
  return false;
}

function getUserId() {
  if (typeof window !== "undefined" && localStorage.getItem("user_id")) {
    try {
      return localStorage.getItem("user_id");
    } catch (e) {
      return "";
    }
  }
  return "";
}

function setUserId(userId) {
  if (typeof window !== "undefined") {
    localStorage.setItem("user_id", userId);
  }
}
