(function () {
  let intervalDuration = 500; //milliseconds
  let languageCode;
  let sierraLoaded = false;

  let getActiveGroups = function() {
    return window.OptanonActiveGroups ? [...window.OptanonActiveGroups.split(',')].filter(activeGroup=> activeGroup.indexOf('C')> -1): new Array();
  }

  let checkOptanonActiveGroups = function(counter){
    counter = counter +1;

    //we are checking for the window.OptanonActiveGroups and it takes time for the groups value to populate
    if (getActiveGroups().length>0) {
      //Call the init method, accepted cookie selection check happens there
      initChatbot();
      //This event is triggerd when the cookie consent is changed and sends the new cookie values to the "optanonLoaded" event of chatBot Component
      window.Optanon.OnConsentChanged(function() {
        initChatbot(); //Call init event again to check if accepted cookies are selected or not when cookie consent is changed
      });
    }
    else{// call again
      if(counter>10){
        console.log('Cookies not found, Stopping the execution here');
        return;
      }
    
      window.setTimeout(()=>{
        checkOptanonActiveGroups(counter);
      }, 	intervalDuration);
    }	
  }

  var initChatbot = function(event){
    //Check for oneTrust cookies selection and if the desired cookies are not accepted, don't load the chatbot
    if(!getActiveGroups().includes('C0001') || !getActiveGroups().includes('C0003')) {
      //Check if widget is already loaded, if yes then hide it and stop the execution
      const hideChatbot = document.querySelector('[data-sierra-chat-launcher]'); // Select the element
      if (hideChatbot) {
        hideChatbot.style.display = 'none'; // Hide it
        sierraLoaded = false;
      }
      return;
    }

    if(sierraLoaded) return;
    // 1. Set the global config
    const configScript = document.createElement('script');
    configScript.text = `
        window.sierraConfig = {
            display: "corner",
            persistence: "cookie",
            language: "${languageCode}",
            cookieDomain: window.location.hostname,
            hideOnClose: true,
            canEndConversation: true,
            launcher: {
                text: "Live Chat",
                icon: "oval"
            },
            dimensions: {
                width: "30em",
                height: "40em"
            }
        };
    `;
    document.head.appendChild(configScript);

    // 2. Load the Sierra SDK
    const sdkScript = document.createElement('script');
    sdkScript.type = 'module';
    sdkScript.src =
      'https://sierra.chat/agent/u3IrRnIBl3t5FJcBl3t5FQrRHlGaxI-mk7Bo3ixh-xQ/custom';

    sdkScript.onload = () => {
      sierraLoaded = true;
    };

    document.head.appendChild(sdkScript);

    //3. Show the chatbot icon if cookie consent is accepted
    const showChatbot = document.querySelector('[data-sierra-chat-launcher]');
    if (showChatbot){
      showChatbot.style.display = 'initial';
    }
  }

  function openChatBot() {
    window.sierra?.openChatModal();  //Out of the box function to open the chatbot on a button click
  }
  // this event will be called from the chatbot component
  document.addEventListener('init_Sierra_Chatbot',(event)=>{
    languageCode = event.detail.language;
    checkOptanonActiveGroups(0);
  });
  //To open the chatbot on button click
  document.addEventListener('openSierraAIChatbot', openChatBot);
})();
