(() => {
  const script = document.currentScript;

  let chatWidgetLoaded = false;

  const appUrl = 'https://maira.gigalogy.com/';
  const serverUrl = 'https://maira.gigalogy.com/';
  let updateMairaIdentifierIntervalId = null;

  let isChatWindowVisible = false; // value 'CLOSED', 'OPEN'
  let isChatWindowFullScreen = false;
  let hostAppScrollProperty;
  const showChatIcon = script.getAttribute("data-show-chat-icon") || "true";
  const enableFeedback = script.getAttribute("data-enable-feedback") || "true";
  const widgetLanguage = script.getAttribute("data-widget-language") || "ja";
  const greeting = script.getAttribute("data-greeting");
  const clientKey = script.getAttribute("data-client-key") || "";
  const dataPrefix = script.getAttribute("data-prefix") || "";
  const chatHeader = script.getAttribute("data-chat-header") || "AI Advisor";
  const iframeBottomPosition = script.getAttribute("data-iframe-bottom-position") || "0";
  const chatIconBottomPosition = script.getAttribute("data-icon-bottom-position") || "20px";
  const commonPositiveFeedbackOptions = script.getAttribute("data-common-positive-feedback-options", "");
  const commonNegativeFeedbackOptions = script.getAttribute("data-common-negative-feedback-options", "");
  const posFbSuccessMsg = script.getAttribute("data-positive-feedback-success-message", "");
  const negFbSuccessMsg = script.getAttribute("data-negative-feedback-success-message", "");
  


  let unreadMessageCount = 0;
  const is_syurui = clientKey === "uEuxYtcROOmfY7WvO3l7JcXmksqyF9p8X6Hen9sNnFM=" || clientKey=="stg-syurui-client-key";

  const loadWidget = () => {
    const api = {
      sendMessage: (message) => {
        iframe.contentWindow.postMessage({
          sendMessage:message
        }, appUrl);
      },

      sendConfig: (message) => {
        iframe.contentWindow.postMessage({
          updateConfig:message
        }, appUrl);
      },
      sendIfDeviceIsMobile: () => {
        const isMobile = window.innerWidth <= 768;
        iframe.contentWindow.postMessage({
            type: "viewport-size",
            deviceType: isMobile ? "mobile" : "notMobile"
          }, appUrl);
      },
      updateIdentifiers: (message) => {
        let index = 0;
        const retry = 20;
        updateMairaIdentifierIntervalId = setInterval(() => {
          if (index < retry) {
            iframe.contentWindow.postMessage({
              updateIds:message
            }, appUrl);
            index++;
          } else {
            clearInterval(updateMairaIdentifierIntervalId);
          }
        }, 200);
      },

      loadConversation: (message) => {
        let index = 0;
        const retry = 5;
        const intervalId = setInterval(() => {
          if (index < retry) {
            iframe.contentWindow.postMessage({
              load:true
            }, appUrl);
            index++;
          } else {
            clearInterval(intervalId);
          }
        }, 500);
      },

      show: () => {
        isChatWindowVisible = true;
        iframe.classList.add('visible');
        if(isChatWindowFullScreen){
          iframe.classList.add('fullscreen');
          document.body.style.overflowY = "hidden";
        }
      },

      hide: () => {
        isChatWindowVisible = false;
        iframe.classList.remove('visible', 'fullscreen');
        if(isChatWindowFullScreen){
          document.body.style.overflow = hostAppScrollProperty;
        }
      },
      enterFullScreen: () => {
        iframe.classList.add('fullscreen');
        isChatWindowFullScreen = true;
        hostAppScrollProperty = document.body.style.overflowY;
        document.body.style.overflowY = "hidden";
      },
      exitFullScreen: () => {
        iframe.classList.remove('fullscreen');
        isChatWindowFullScreen = false;
        document.body.style.overflow = hostAppScrollProperty;
      },

      toggle: () => {
        if(isChatWindowVisible){
          api.hide();
        }
        else {
          api.show();
          api.hideBadge();
        }
      },

      hideBadge: () => {
        unreadMessageCount = 0;
        badge.textContent = unreadMessageCount;
        badge.style.display = "None";
      },

      showBadge: () => {
        badge.textContent = unreadMessageCount;
        badge.style.display = "flex";
      },
      
    }

    const widget= document.createElement("div");

    const widgetStyle = widget.style;
    // widgetStyle.display = "none";
    // widgetStyle.boxSizing = "border-box";
    // widgetStyle.position = "fixed";
    // widgetStyle.bottom = "20px";
    // widgetStyle.right = "40px";

    // Create an img element for the SVG icon
    const svgIcon = document.createElement("img");

    let iconColor = script.getAttribute("data-icon-color");
    const encodedColor = encodeURIComponent(iconColor);
    // Create a container div for the SVG icon
    const iconContainer = document.createElement("div");
    iconContainer.id = "mairaAIadvisorSvg";
    iconContainer.style.borderRadius = "50%";
    iconContainer.style.backgroundColor = iconColor;

    // Append the SVG icon to the container
    iconContainer.appendChild(svgIcon);
    Object.assign(iconContainer.style, { 
      width: is_syurui ? 'clamp(110px, 8vw, 158px)' : 'clamp(32px, 4vw, 44px)', 
      height: is_syurui ? 'clamp(110px, 8vw, 158px)' : 'clamp(32px, 4vw, 44px)', 
      padding: is_syurui ? '1px ' : 'clamp(12px, 3vw, 16px)'
    });
// Create the SVG markup directly
    const svgMarkup = `
  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="16" height="16">
    <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 13.5997 2.37562 15.1116 3.04346 16.4525C3.22094 16.8088 3.28001 17.2161 3.17712 17.6006L2.58151 19.8267C2.32295 20.793 3.20701 21.677 4.17335 21.4185L6.39939 20.8229C6.78393 20.72 7.19121 20.7791 7.54753 20.9565C8.88837 21.6244 10.4003 22 12 22Z" fill="white"></path>
    <path d="M15 12C15 12.5523 15.4477 13 16 13C16.5523 13 17 12.5523 17 12C17 11.4477 16.5523 11 16 11C15.4477 11 15 11.4477 15 12Z" fill="${iconColor}"></path>
    <path d="M11 12C11 12.5523 11.4477 13 12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12Z" fill="${iconColor}"></path>
    <path d="M7 12C7 12.5523 7.44772 13 8 13C8.55228 13 9 12.5523 9 12C9 11.4477 8.55228 11 8 11C7.44772 11 7 11.4477 7 12Z" fill="${iconColor}"></path>
  </svg>
    `;

    const svgCrossMarkup = `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M19 5L4.99998 19M5.00001 5L19 19" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    `;

    // Set the SVG markup as the src of the img element
    if (is_syurui) {
      svgIcon.src = appUrl+'chat-image/AI.png';
      svgIcon.style.borderRadius = "50%";

    }else{
      svgIcon.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgMarkup)}`;
    }
    svgIcon.alt = "Chat Icon";
    svgIcon.style.width = "100%"; // Adjust the width as needed

    iconContainer.style.position = "fixed";
    iconContainer.style.bottom = chatIconBottomPosition;
    iconContainer.style.right = "20px"; // Adjust the right distance as needed
    iconContainer.style.cursor = "pointer";
    iconContainer.style.zIndex = 999999;
    svgIcon.style.backgroundColor = iconColor;
    iconContainer.style.transition = "transform 0.3s ease-in-out";
    iconContainer.style.setProperty("box-sizing", "content-box", "important");
    iconContainer.style.borderRadius = "50%"; // Ensures the icon is round
    // svgIcon.style.boxShadow = "0 4px 4px rgba(0, 0, 0, 0.3)"; // Circular shadow

    // Apply the shadow properties
    iconContainer.style.boxShadow = "0 25px 50px -12px rgba(0, 0, 0, 0.5)";
    iconContainer.style.setProperty("--tw-ring-inset", "");
    iconContainer.style.setProperty("--tw-ring-offset-width", "0px");
    iconContainer.style.setProperty("--tw-ring-offset-color", "#fff");
    iconContainer.style.setProperty("--tw-ring-color", "rgba(59, 130, 246, 0.5)");
    iconContainer.style.setProperty("--tw-ring-offset-shadow", "0 0 #0000");
    iconContainer.style.setProperty("--tw-ring-shadow", "0 0 #0000");
    iconContainer.style.setProperty("--tw-shadow", "0 0 #0000");
    iconContainer.style.setProperty("--tw-shadow-colored", "0 0 #0000");

    iconContainer.addEventListener("mouseenter", () => {
      iconContainer.style.transform = "scale(1.1)";
    });

    iconContainer.addEventListener("mouseleave", () => {
      iconContainer.style.transform = "scale(1)";
    });

    iconContainer.addEventListener("click", () => {
      iconContainer.style.transform = "scale(1)";
      if(!chatWidgetLoaded){
        api.loadConversation();
        chatWidgetLoaded=true;
      }
      api.toggle();
    });

    const badge = document.createElement("span");
    badge.style.position = "absolute";
    badge.style.top = "-6px"; // Adjust top position to align badge
    badge.style.right = "-3px"; // Adjust right position to align badge
    badge.style.height = "1.3rem"; // Slightly increased height
    badge.style.width = "1.3rem"; // Slightly increased width
    badge.style.fontSize = "0.65rem"; // Slightly increased font size
    badge.style.lineHeight = "1.3rem"; // Line height matches height
    badge.style.backgroundColor = "#fa3e3e"; // Background color
    badge.style.color = "rgb(255, 255, 255)"; // Text color
    badge.style.borderRadius = "50%"; // Make badge circular
    badge.style.padding = "3px"; // Adjust padding for spacing
    badge.style.display = "None";
    badge.style.justifyContent = "center";

    if(unreadMessageCount){
      badge.textContent = unreadMessageCount; // Set the badge text (e.g., number of notifications)
    }
    iconContainer.appendChild(badge);

    if(showChatIcon === 'false'){
      iconContainer.style.display = "none";
    }
    widget.appendChild(iconContainer);
    const iframe = document.createElement("iframe");

    // Set the id for the dynamically created iframe
    iframe.id = "mairaAIadvisorIframe";
    iframe.allow = "clipboard-write";
    const iframeStyle = iframe.style;
    iframeStyle.boxSizing = "borderBox";
    iframeStyle.position = "fixed";
    iframeStyle.width = '22vw';
    iframeStyle.zIndex = 999999;
    iframeStyle.border = 0;
    iframeStyle.bottom = iframeBottomPosition;
    iframeStyle.right = "10px"; /* Adjust as needed */
    iframeStyle.opacity = "0"; /* Initially hidden */
    iframeStyle.transition = "opacity 0.3s ease-in-out, transform 0.3s ease-in-out";
    // iframeStyle.backgroundColor = "white";
    widget.appendChild(iframe);

    const style = document.createElement("style");
    style.textContent = `
    @media screen and (min-width: 769px) {
        #mairaAIadvisorIframe {
          height: 84vh !important;
          min-width: 404px !important;
          max-height: 620px !important;
          background-color: transparent !important;
          transform: translate(50%, 50%) scale(0.1);
          opacity: 0;
          transition: all 0.3s ease !important; 
        }
        
       #mairaAIadvisorIframe.visible {
          transform: translate(0, -100px) scale(1) !important;
          opacity: 1 !important;
        }
        #mairaAIadvisorIframe.fullscreen {
          width: 100% !important;
          height: 100% !important;
          max-height: 100% !important;
          min-width: 0 !important;
          background-color: white !important;
          right: 0px !important;
          bottom: 0px !important;
          transform: translate(0, 0) scale(1) !important;
          opacity: 1 !important;
        }
    }
    @media screen and (max-width: 768px){
        #mairaAIadvisorIframe {
            width: 100% !important;
            height: 100% !important;
            min-width: auto !important;
            right: 0px !important;
            bottom: 0px !important;
            transform: translateY(100%) scale(.1); 
        }
        
        #mairaAIadvisorIframe.visible {
          transform: translate(0, 0) scale(1) !important; 
          opacity: 1 !important;
        }
    }
    `;
    document.head.appendChild(style);

    window.addEventListener("message", (evt) => {
      if(evt.data === "enterFullScreen") {
        api.enterFullScreen();
      }
      if(evt.data === "exitFullScreen") {
        api.exitFullScreen();
      }
      if (evt.data === "hide") {
        api.hide();
      }

      if (evt.data && evt.data.type === 'contentReady') {
        iframe.contentWindow.postMessage({ greeting }, appUrl);
      }

      if (evt.data && evt.data.type === 'updateIdsOk') {
        // console.log('Ok');
        clearInterval(updateMairaIdentifierIntervalId);
      }

      if (evt.data && evt.data.type === 'incomingMessage') {
        if(!isChatWindowVisible){
          unreadMessageCount++;
          api.showBadge();
        }
      }
      if(evt.data && evt.data.type === 'isMobile'){
        api.sendIfDeviceIsMobile();
      }
    });
    window.addEventListener("resize", api.sendIfDeviceIsMobile);

    iframe.addEventListener("load", () => {
      window.addEventListener("getWidgetApi", () => {
        const event = new CustomEvent('widgetApi', {detail: api});
        window.dispatchEvent(event);

      });
    });

    const params = new URLSearchParams({
      clientKey: clientKey,
      dataPrefix: dataPrefix,
      chatHeader: chatHeader,
      enableFeedback: enableFeedback,
      lang: widgetLanguage,
      posFeedbackOptions: commonPositiveFeedbackOptions,
      negFeedbackOptions: commonNegativeFeedbackOptions,
      posFbSuccessMsg: posFbSuccessMsg,
      negFbSuccessMsg: negFbSuccessMsg
    });

    const widgetUrl = `${appUrl}plugin?${params.toString()}`;
    iframe.src = widgetUrl;
    document.body.appendChild(widget);
  }

  if ( document.readyState === "complete" ) {
    loadWidget();
  } else {
    document.addEventListener("readystatechange", () => {
      if ( document.readyState === "complete" ) {
        loadWidget();
      }
    });
  }
})();
