window.addEventListener('load', function () { 
window.code = "243262243130246c42395a33355352386d7863412f516939796c732e65315271534c66597778326f4e58636a5a38614b454b7a733652394474474f4b"; 
window.roomKey = "null"; 
window.userIP = "148.170.233.87"; 
window.templateFormat = "dynamic"; 
// Only load window once
if (window.__CBW_INITED__) {
  console.warn("CBW already initialized, skipping");
  return;
}
window.__CBW_INITED__ = true;

window.apiPath = 'https://chatapi.answeringlegal.com/';
window.socketPath = 'wss://chatapi.answeringlegal.com';
window.chatbotPosition = window.chatbotPosition || "right";

window.template_code = window.code || "2432622431302435534f3646686b71303135484d623353416a354848656f2f37364534744f4f59574858756f42423138335a503966476a6e354e6a6d";
window.questionInfo = {};
window.questionCount = 0;
let currentUrl = window.location.href;
window.url = new URL(currentUrl);

window.relatedPath = 'https://chat.answeringlegal.com/chatboat/chat_bot.gif';
window.defaultLogo = 'https://chat.answeringlegal.com/chatboat/chatbot_assistant.png';

window.frontEndDefaultPath = "";
window.timeCounter = 0;
window.loaderCount = 0;
window.responseError = false;
window.ideal = false;
window.intervalId = "";
window.SESSION_TIMEOUT_MINUTES = 2
window.roomKey = localStorage.getItem("roomKey")
// window.isTimeOver = false;
window.currentEpochTime = Date.now();
window.connectionLink =  [];
window.calendlyL = "https://calendly.com/deepti-khushalani-ecosmob/ecosmob-meeting";
window.calendlyLink = "";
window.calendlyEmail = "";
window.calendlyName = "";
window.embedeCss = 'https://chat.answeringlegal.com/chatboat/style.css';

// SHADOW DOM 
const encompassingChatContainer = document.createElement("div");
encompassingChatContainer.id = "cbw__shadow";
window.shadow = encompassingChatContainer.attachShadow({ mode: "open" });
document.body.appendChild(encompassingChatContainer);

// VARIABLE
const varibaleScript = document.createElement("script");
varibaleScript.src += "https://chat.answeringlegal.com/chatboat/variable.js";
varibaleScript.onload = function() {
    window.socketPath = socketPath;
    window.apiPath = apiPath;
    // window.relatedPath = relatedPath;
    // window.defaultLogo = defaultLogo;
    window.frontEndDefaultPath = frontEndDefaultPath;
    window.embedeCss = embedeCss;
};
window.shadow.appendChild(varibaleScript);

// calendly 
const calendlyScript = document.createElement("script");
calendlyScript.src += "https://assets.calendly.com/assets/external/widget.js";
window.shadow.appendChild(calendlyScript);

// external Font css
const externalFontCss = document.createElement("style");
externalFontCss.href = window.embedeCss;
window.shadow.appendChild(externalFontCss);

// embed css
// const link = document.createElement('link');
// link.rel = 'stylesheet';
// link.href = 'https://answeringlegal.ecosmob.net/chatboat/style.css';                           
// link.type = 'text/css';
// window.shadow.appendChild(link);

window.questionList = [];

// Create a meta element
var metaCacheControl = document.createElement('meta');
metaCacheControl.setAttribute('http-equiv', 'Cache-Control');
metaCacheControl.setAttribute('content', 'no-cache, no-store, must-revalidate');

// Create another meta element for Pragma
var metaPragma = document.createElement('meta');
metaPragma.setAttribute('http-equiv', 'Pragma');
metaPragma.setAttribute('content', 'no-cache');

// Create a meta element for Expires
var metaExpires = document.createElement('meta');
metaExpires.setAttribute('http-equiv', 'Expires');
metaExpires.setAttribute('content', '0');

// Append all meta tags to the head
window.shadow.appendChild(metaCacheControl);
window.shadow.appendChild(metaPragma);
window.shadow.appendChild(metaExpires);

const markedJs = document.createElement("script");
markedJs.src += "https://cdn.jsdelivr.net/npm/marked/marked.min.js";
window.shadow.appendChild(markedJs);

sessionStorage.setItem("isChatOngoing", "true")

window.staticReady = false;
window.pendingStartChat= false;

const questionScript = document.createElement("script");
questionScript.innerHTML += `

const loadServiceWorker = (scriptUrl) => {
    const scriptTag = document.createElement('script');
    scriptTag.src = scriptUrl;

    window.shadow.appendChild(scriptTag);

    scriptTag.onload = () => {
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register(scriptUrl)
          .then((registration) => {
            console.log('Service Worker registered with scope:', registration.scope);
          })
          .catch((error) => {
            console.error('Service Worker registration failed:', error);
          });
      } else {
        console.log('Service Workers are not supported in this browser.');
      }
    };

    scriptTag.onerror = (error) => {
      console.error('Error loading the Service Worker script:', error);
    };
  };

  // TODO No service worker for now
  // loadServiceWorker('./service-worker.js');

function applyChatbotPosition() {
    const startBtn = window.shadow.querySelector(".cbw__bot-start-btn");
    const body = window.shadow.querySelector(".cbw__body");

    const side = window.chatbotPosition === "left" ? "left" : "right";
    const x = 20;
    const y = 20;

    if (startBtn) {
        startBtn.style.bottom = y + "px";
        startBtn.style.left = side === "left" ? x + "px" : "auto";
        startBtn.style.right = side === "right" ? x + "px" : "auto";
    }

    if (body) {
        body.style.bottom = y + "px";
        body.style.left = side === "left" ? x + "px" : "auto";
        body.style.right = side === "right" ? x + "px" : "auto";
    }
}

function generateUniqueCode() {
    let code = '';
    let isRoomKey = localStorage.getItem("roomKey");
    console.log("window.roomKey 111 :::",isRoomKey, "----");
    console.log("window.roomKey 111 sessionStorage['roomKey'] ::: ", sessionStorage.getItem("roomKey"));

    if(isRoomKey == null && isRoomKey == undefined) {
        console.log("window.roomKey 222 ::: ", isRoomKey);
        code = dynamiCode();
        window.roomKey = code;
        console.log("window.roomKey ::: ", code);
    } 
    else {
        if(isRoomKey == null) {
            console.log("window.roomKey else ::: ", isRoomKey);
            code = dynamiCode();
        } else {
            code = isRoomKey;
        }
    }
    
    return code;
}

function dynamiCode() {
    let code = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A';
    for (let i = 0; i < 15; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        code += chars[randomIndex];
    }

    localStorage.setItem("roomKey", code);
    sessionStorage['roomKey'] = code;
    console.log("sessionStorage['roomKey'] ::: ", sessionStorage['roomKey']);

    return code;
}

let validation;
function displayErrorMassage(){
   window.shadow.getElementById("errorMessage").innerText=validation;
}

function loadChat(isChatExists = false) {

    var messageInput = window.shadow.getElementById('messageInput');
    setTimeout(scrollToBottom, 100);
    messageInput.value = '' ;
    messageInput.style.height =  '26px';
    var inputBox = window.shadow.querySelector(".cbw__footer");
    inputBox.classList.remove('show');
    inputBox.classList.add('hide');
    var sendBtn = window.shadow.querySelector('.cbw__send-btn');
    sendBtn.classList.remove('transform-div');

    if (
      window.ideal === false &&
      (
        window.templateFormat === 'dynamic' ||
        (window.templateFormat === 'static' && window.staticReady === true)
      )
    ) {

        const timeOut =  window.questionCount  === 0 ? 1000 : 0;
        var chat = window.shadow.querySelector('.cbw__chat');
        var cbwBody = window.shadow.querySelector(".cbw__body");

        // ON MAXIMIZE DISPLAY CHAT
        console.log("window.questionList.length", window.questionList.length)
        console.log("window.questionList.length", window.questionList)

        // if(window.questionList.length == 0) {
            chat.innerHTML = '';
            var loaderContainer = document.createElement('div');
            loaderContainer.className = 'cbw__receiver-msg-box';
            loaderContainer.id = 'first-loader';
            loaderContainer.innerHTML = \`
                                    <p class="cbw__receiver-msg">
                                        <span class="loader"></span>
                                    </p>
                                \`;
            chat.append(loaderContainer);
        // }

        setTimeout(() => {

            const message = {answer: 'ecosmob#anaweringlegal@chatbotwidget', template_code: window.template_code};
            console.log("------------", localStorage.getItem("isFirstLoaded"))
            if(localStorage.getItem("isFirstLoaded") == null && localStorage.getItem("isFirstLoaded") == undefined){
                
                const isLoaderExists = window.shadow.getElementById('first-loader');
                if(isLoaderExists) {
                    isLoaderExists.classList.add('hide');
                }
                
                const isClickHereExists = window.shadow.getElementById('error');
                if(isClickHereExists) {
                    isClickHereExists.classList.add('hide');
                }

                //  STATIC CONDITON COMMENT
 
                if(window.templateFormat === 'static'){
                    window.questionList.push(message);
                }

                window.ws.send(JSON.stringify(message));
                clearInterval(window.intervalId);
                window.loaderCount = window.loaderCount + 1;

                setCurrentEpochTime();

                // window.timeCounter = 0;
                // broadcastMessage(0, "timeCounter");
                // localStorage.setItem("timeCounter", 0);
                
                loaderDisplay();
            }
        }, timeOut);

        var cbwBody = window.shadow.querySelector(".cbw__body");
        if (cbwBody.classList.contains('show')) {
            var botStartBtn = window.shadow.querySelector(".cbw__bot-start-btn")
            botStartBtn.classList.add('hide');
            botStartBtn.classList.remove('show');

            if(window?.questionInfo?.answerType === "Input_box") {
                inputBox.classList.remove('hide');
                inputBox.classList.add('show');
            }

            //NOTE: after closing open ai chatbot with input box
            if(window?.questionInfo?.message) {
                inputBox.classList.remove('hide');
                inputBox.classList.add('show');
            }

            if(localStorage.getItem("isFirstLoaded") != null && localStorage.getItem("isFirstLoaded") != undefined && (!window.isTimeOver)){
                chatHistoryLoad();
            }    

            // IS TIME OVER THEN DISPLAY CLICK HERE MSG
            console.log("::: window.isTimeOver", window.isTimeOver)
            if(window.isTimeOver) {
                displayErrorMessage();

                // IS TIME OVER THEN HIDE INPUT
                var inputBox = window.shadow.querySelector(".cbw__footer");
                inputBox.classList.remove('show');
                inputBox.classList.add('hide');
            }
        }
    } else {        
        var botStartBtn = window.shadow.querySelector(".cbw__bot-start-btn")
        botStartBtn.classList.add('hide');
        botStartBtn.classList.remove('show');
        chatHistoryLoad();
    }
}

function chatHistoryLoad() {

    let chatData = localStorage.getItem('chatData');
    if(chatData && chatData.length > 0 &&  (window?.questionInfo?.responseType != "chat_history" && window?.questionInfo?.responseType != "partial_chat")) {
        
        chatData = JSON.parse(chatData);
        console.log("show hide chat", chatData)
        window.shadow.querySelector('#chat-container #first-loader').style.display = 'none';

        let filteredData = Array.from(new Map(chatData.map(item => [item.question_id, item])).values());

        // let uniqueQuestionsFromYou = new Set(chatData.filter(item => item.sender === 'you').map(item => item.question_id));
        // let filteredData = chatData.filter(item => {
        //     return !uniqueQuestionsFromYou.has(item.question_id) || item.sender === 'you';
        // });

        console.log(filteredData);

        // (filteredData).forEach((item) => { NOTE: this removes first message when refresh
        (chatData).forEach((item) => {

            const subchatHistory = window.shadow.querySelector('.cbw__chat');
            let subreceiverMainContainer = document.createElement('div');
            subreceiverMainContainer.className = 'cbw__chat_history';
            subreceiverMainContainer.id = 'chat-container_history';
            
            let receiverHtmlSub = '';
            let usersubChatHistorySub = '';

            if( item.answerType == 'Lead_Collection_Form') {
                const receiverHtmlSub1 = getQuestionData(item?.answerType ,item?.answers?.[0]?.paramValue, item?.answers?.[0]?.hyperLink, item, item?.questions?.[0]?.formTitle);
                subchatHistory.append(receiverHtmlSub1);
            }
            
            // BOT MESSAGE
            if((!!item.question)  && (item.answerType == 'Input_box' || item.answerType == 'End_Chat' || item.answerType == 'No_Answer' )) {
                receiverHtmlSub = botTextMessages(item);

                if(item.answer != '' && item.answer != null && item.answer != undefined) {
                    usersubChatHistorySub = userTextMessages(item);
                }
            }

            // BOT RADIO MESSAGE
            if((!!item.question)  && (item.answerType == 'Selectable_Option')) {
                receiverHtmlSub = botRadioMessages(item);

                if(item.answer != '' && item.answer != null && item.answer != undefined) {
                    usersubChatHistorySub = userTextMessages(item);
                }
            }
            
            // BOT DROPDOWN MESSAGE
            if((!!item.question)  && (item.answerType == 'Searchable_Dropdown')) {
                receiverHtmlSub = botDropDownMessages(item);

                if(item.answer != '' && item.answer != null && item.answer != undefined) {
                    usersubChatHistorySub = userTextMessages(item);
                }
            }

            // AI text response
            if(item.chaType == "ai"){    
              if(Boolean(item.question)){
                receiverHtmlSub = botTextMessages(item);
              }          
                
              if(Boolean(item.answer)){
                // usersubChatHistorySub = userTextMessages(item);
                usersubChatHistorySub = userTextMessagesAI(item);  // fix: same spacing after refresh
              }
            }            

            // USER FILE UPLOAD
            if((!!item.question)  && (item.answerType == 'file' || item.answerType == 'File_Upload')) {
                receiverHtmlSub = botTextMessages(item);

                if(item.answer != '' && item.answer != null && item.answer != undefined) {
                    if(window.templateFormat === "static") {      // file path different for each template type           
                        usersubChatHistorySub = prepareFileUploadMessage({
                            fileName: item.fileName,
                            uploadStatus: "LOAD_FROM_HISTORY",
                            fileUrl: item.answer
                        });
                    } else {
                        usersubChatHistorySub = prepareFileUploadMessage({
                            fileName: item.fileName,
                            uploadStatus: "LOAD_FROM_HISTORY",
                            fileUrl: item.fileUpload
                        });                     
                    }                       
                }
            }

            subreceiverMainContainer.innerHTML += receiverHtmlSub
            subreceiverMainContainer.innerHTML += usersubChatHistorySub;
            subchatHistory.append(subreceiverMainContainer);

        });
    }
    
    if((!!window?.questionInfo?.responseType) && (window?.questionInfo?.responseType == "chat_history" || window?.questionInfo?.responseType == "partial_chat")) {

        window.shadow.querySelector('#chat-container #first-loader').style.display = 'none';
        
        //bring back input after refresh + toggle
        const inputBox = window.shadow.querySelector(".cbw__footer");
        inputBox.classList.add('show');
        inputBox.classList.remove('hide');
        
        console.log("::: chatHistoryLoad partial_chat")
        const chatHistory = window.shadow.querySelector('.cbw__chat');

        let receiverMainContainer = document.createElement('div');
        receiverMainContainer.className = 'cbw__chat_history';
        receiverMainContainer.id = 'chat-container_history';

        (window?.questionInfo?.chats).forEach((item) => {    
            
            let receiverHtml = '';
            let userChatHistory = '';
            
            // BOT MESSAGE
            if((!!item.question)  && (item.answerType == 'Input_box' || item.answerType == 'End_Chat'  || item.answerType == 'No_Answer'  )) {
                receiverHtml = botTextMessages(item);
                
                if(item.answer != '') {
                    userChatHistory = userTextMessages(item);
                }
            }

            // BOT RADIO MESSAGE
            if((!!item.question)  && (item.answerType == 'Selectable_Option')) {
                receiverHtml = botRadioMessages(item);

                if(item.answer != '') {
                    userChatHistory = userTextMessages(item);
                }
            }
            
            // BOT DROPDOWN MESSAGE
            if((!!item.question)  && (item.answerType == 'Searchable_Dropdown')) {

                receiverHtml = botDropDownMessages(item);

                if(item.answer != '') {
                    userChatHistory = userTextMessages(item);
                }
            }

            if(window.templateFormat == 'dynamic'){
              if(Boolean(item.question)){
                receiverHtml = botTextMessages(item);
              }          
                
              if(item.answerType === 'file' && item.fileUpload && item.fileName) {
                userChatHistory = prepareFileUploadMessage({
                    fileName: item.fileName,
                    uploadStatus: "LOAD_FROM_HISTORY",
                    fileUrl: item.fileUpload
                });
              } else if(Boolean(item.answer)){
                // userChatHistory = userTextMessages(item);
                userChatHistory = userTextMessagesAI(item);  // fix: same spacing after refresh
              }            
            }     
              
            // static file upload
            // if(window.templateFormat == 'static'){
            //   if(Boolean(item.question)){
            //     receiverHtml = botTextMessages(item);
            //   }          
                
            //   if(item.answerType === 'File_Upload' && item.answer && item.fileName) {
            //     userChatHistory = prepareFileUploadMessage({
            //         fileName: item.fileName,
            //         uploadStatus: "LOAD_FROM_HISTORY",
            //         fileUrl: item.answer
            //     });
            //   } else if(Boolean(item.answer)){
            //     userChatHistory = userTextMessages(item);
            //   }            
            // }                 

            receiverMainContainer.innerHTML += receiverHtml
            receiverMainContainer.innerHTML += userChatHistory;
            chatHistory.append(receiverMainContainer);
        });   
    }
}

function botTextMessages(item) {

    const linkUrl =  item?.hyperLink?.[0]?.url;
    const linkText =  item?.hyperLink?.[0]?.textToBeLinked;

    let linkCalendarData = ''; 
    if (!!linkUrl) {
        linkCalendarData = \` <div class="cbw__receiver-msg-box pointer-event" style="position: relative;" id="">
            <div class="" data-type="receiver-msg">
                <p class="cbw__receiver-msg">
                    <span>
                        \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')}
                    </span>
                </p>
            </div>
        </div> \`;

    } else {
        // NOTE: before marked preview on toggle chatbot line:447-451
        // <p class="cbw__receiver-msg">
        //     \${item.question}
        // </p>
        linkCalendarData = \` <div class="cbw__receiver-msg-box pointer-event" style="position: relative;" id="">
            <div class="" data-type="receiver-msg">
                <span class="cbw__receiver-msg">
                    <pre class="cbw__receiver-msg-pre">
                        \${(window.marked && window.marked.parse)
                            ? window.marked.parse(item.question)
                            : item.question}
                    </pre>
                </span>
            </div>
        </div> \`;
    }

    return linkCalendarData;
}

function botRadioMessages(item) {

    const linkUrl =  item?.hyperLink?.[0]?.url;
    const linkText =  item?.hyperLink?.[0]?.textToBeLinked;

    let linkCalendarData = ''; 
    if (!!linkUrl) {
        linkCalendarData = \`  <div class="cbw__receiver-msg-box" data-type="receiver-msg-option-list" id="" style="margin:10px 0px;">
                <div class="cbw__receiver-msg">
                    <span> \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')} </span>
                    <div class="cbw__option-list-box custom-scrollbar">
                        <div class="cbw__option-list-radio">
                            <input type="radio" class="select-btn" name="optionRadio" id="991-0" hidden="" checked>
                            <label for="991-0">
                                \${item.answer}
                            </label>
                        </div>      
                    </div>
                </div>
            </div> \`;

    } else {
        if(item?.answers?.[0]?.paramValue?.length > 0) {
            linkCalendarData  = \` <div class="cbw__receiver-msg-box" data-type="receiver-msg-option-list" id="" style="margin:10px 0px;">
                <div class="cbw__receiver-msg">
                        \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')}
                    <div class="cbw__option-list-box custom-scrollbar">
                    \`;
                        for(let i=0; i<item?.answers?.[0]?.paramValue?.length; i++) {
                            linkCalendarData += 
                                \`
                                    <div class="cbw__option-list-radio">
                                        <input type="radio" class="select-btn" name="optionRadio" id="\${window.questionInfo?.question_id + '-' + i}" hidden>
                                        <label for="\${window.questionInfo?.question_id + '-' + i}">
                                            \${item?.answers?.[0]?.paramValue[i].value}
                                        </label>
                                    </div>
                                \`  
                        }
            linkCalendarData += \` </div> </div> </div> \`;
        } else {

            linkCalendarData = \`  <div class="cbw__receiver-msg-box" data-type="receiver-msg-option-list" id="" style="margin:10px 0px;">
                    <div class="cbw__receiver-msg">
                        \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')}
                        <div class="cbw__option-list-box custom-scrollbar">
                            <div class="cbw__option-list-radio">
                                <input type="radio" class="select-btn" name="optionRadio" id="991-0" hidden="" checked>
                                <label for="991-0">
                                    \${item.answer}
                                </label>
                            </div>      
                        </div>
                    </div>
                </div> \`;
        }

    }

    return linkCalendarData;
}

function botDropDownMessages(item) {
    
    const linkUrl =  item?.hyperLink?.[0]?.url;
    const linkText =  item?.hyperLink?.[0]?.textToBeLinked;

    let linkDropDownData = ''; 
    if (!!linkUrl) {

        linkDropDownData = \` <div class="cbw__receiver-msg-box" data-type="receiver-msg" style="margin:10px 0px;">
                <div class="cbw__receiver-msg">
                    <span> \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')} </span>
                </div>
            </div> 
            
            <div id="1068" class="custom-select">
                <select id="dropdown" class="dropdown">
                    <option value="" class="dropdown-option-btn">Select</option>
                    <option class="dropdown-option-btn" selected> \${item.answer == null && item.answer == undefined ? 'Select' : item.answer} </option>
                </select>
                <div class="select-selected" id="select-selected">\${item.answer == null && item.answer == undefined ? 'Select' : item.answer}</div>
                <div class="select-items select-hide">
                    <div> \${item.answer == null && item.answer == undefined ? 'Select' : item.answer} </div>
                </div>
            </div>\`;
                
    } else {

        if(item?.answers?.[0]?.paramValue?.length > 0) {
            linkDropDownData = '';
            nextQuestionPrepare(item);
        } else {

            linkDropDownData = \` <div class="cbw__receiver-msg-box" data-type="receiver-msg" style="margin:10px 0px;">
                <div class="cbw__receiver-msg">
                \${item?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>')}
                </div>
            </div> 
            
            <div id="1068" class="custom-select">
                <select id="dropdown" class="dropdown">
                    <option value="" class="dropdown-option-btn">Select</option>
                    <option class="dropdown-option-btn" selected> \${item.answer == null && item.answer == undefined ? 'Select' : item.answer} </option>
                </select>
                <div class="select-selected" id="select-selected">\${item.answer == null && item.answer == undefined ? 'Select' : item.answer}</div>
                <div class="select-items select-hide">
                    <div> \${item.answer == null && item.answer == undefined ? 'Select' : item.answer} </div>
                </div>
            </div>\`;
        }
    }

                
    return linkDropDownData;
}

function userTextMessages(item) {
    let userChatHistory = \` <div class="cbw__sender-msg-box" id="">
                <p class="cbw__sender-msg">
                    \${item.answer}
                </p>
        </div> \`

    return userChatHistory;
}

function userTextMessagesAI(item) {
    let userChatHistory = \` <div class="cbw__sender-msg-box" id="">
                <div class="cbw__sender-msg">
                    <p>
                    \${item.answer}
                    </p>
                </div>
        </div> \`

    return userChatHistory;
}

function getQuestionData(type, data, linkData, leadCollection, title) {
    window.questionCount = window.questionCount + 1;
    if(type !== 'End_Chat' && type !== 'No_Answer') {
        setIntervalFunc();
    }

    // HIDE LEAD FORM ALL TAB
    if (document.visibilityState == 'hidden') {
        const leadFormSection = window.shadow.querySelector('.lead-form-section');
        if (leadFormSection) {
            leadFormSection.style.display = 'none'; 
        }
    }

    var questionId = window?.questionInfo?.question_id;
    var tempContainer = document.createElement('div');
    if(type !== 'Selectable_Option' && type !== 'Searchable_Dropdown' && type !== 'Calender' && type !== 'Lead_Collection_Form') {
        var chat = window.shadow.querySelector('.cbw__chat');
        // var questionContainer = document.createElement('div');
        tempContainer.className = 'cbw__receiver-msg-box';
        tempContainer.style.position = 'relative'; 
        tempContainer.id = questionId;

        let linkHtmlData = '';
        if(linkData.length > 0){

            const linkUrl = linkData[0]?.url;
            const linkText = linkData[0]?.textToBeLinked;
            linkHtmlData += '<span>' ;
            linkHtmlData += window.questionInfo?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>');
            linkHtmlData += '<\span>' ;

        } else {
            linkHtmlData = window.questionInfo?.question;
        }

        tempContainer.innerHTML += \`<div class="" data-type="receiver-msg">
            <p class="cbw__receiver-msg">
                \${linkHtmlData}
            </p>
        </div>\`;
        setTimeout(scrollToBottom, 100);
    }


    let typeData = '';
    if(type === 'Selectable_Option' || type === 'radio') {
        
        let linkSelectableHtmlData = '';
        if(linkData.length > 0){

            const linkUrl = linkData[0]?.url;
            const linkText = linkData[0]?.textToBeLinked;
            linkSelectableHtmlData += '<span>' ;
            linkSelectableHtmlData += window.questionInfo?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>');
            linkSelectableHtmlData += '<\span>' ;

        } else {
            linkSelectableHtmlData = window.questionInfo?.question;
        }

        tempContainer.className = 'cbw__receiver-msg-box';
        tempContainer.dataset.type = 'receiver-msg-option-list';
        tempContainer.id = questionId;
        let optionsHTML  = \`
                <div class="cbw__receiver-msg">
                    \${linkSelectableHtmlData}
                    <div class="cbw__option-list-box custom-scrollbar">
                    \`;
                        for(let i=0;i<data?.length;i++) {
                            optionsHTML += 
                                \`
                                    <div class="cbw__option-list-radio">
                                        <input type="radio" class="select-btn" name="optionRadio" id="\${window.questionInfo?.question_id + '-' + i}" hidden>
                                        <label for="\${window.questionInfo?.question_id + '-' + i}">
                                            \${data[i].value}
                                        </label>
                                    </div>
                                \`  
                        }
            optionsHTML += 
            \`   
                    </div>
                </div>
        \`;
        tempContainer.innerHTML = optionsHTML;

    } else if(type === 'Searchable_Dropdown') {

        let linkDropDownHtmlData = '';
        if(linkData.length > 0){

            const linkUrl = linkData[0]?.url;
            const linkText = linkData[0]?.textToBeLinked;
            linkDropDownHtmlData += '<span>' ;
            linkDropDownHtmlData += window.questionInfo?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>');
            linkDropDownHtmlData += '<\span>' ;

        } else {
            linkDropDownHtmlData = window.questionInfo?.question;
        }

        tempContainer.className = 'cbw__receiver-msg-box';
        tempContainer.dataset.type = 'receiver-msg';
        let optionsHTML = \`
            <div class="cbw__receiver-msg">
            \${linkDropDownHtmlData}
            </div>
        \`;
        tempContainer.innerHTML = optionsHTML;
    
    } else if(type === 'Lead_Collection_Form'){
                    
        
        tempContainer.innerHTML = leadcollectionbody(leadCollection?.questions, title);
       setTimeout(() => {
        const requiredAnswerTypes = ["Input_box", "Selectable_Option","Searchable_Dropdown"];
                const answerTypesInData = leadCollection?.questions.map(item => item.answerType);
                const hasInputBox = answerTypesInData.includes("Input_box");
                const hasSelect = answerTypesInData.includes("Selectable_Option");
                const hasRadio = answerTypesInData.includes("Searchable_Dropdown");

           const settingButtonform = window.shadow.getElementById('form-lead-collection');
          if (settingButtonform) {

        settingButtonform.addEventListener('click', function (event) {
            event.preventDefault();

            let services = [];
            let isValid = true;  // Flag to check validation

            // Validate Text Inputs (e.g., Input box)
            // const getInputData = document.getElementsByClassName('leadInputType');
            const getInputData = window.shadow.querySelectorAll('.leadInputType');
            
            if (getInputData.length > 0) {
                Array.from(getInputData).forEach((input) => {
                    if (input?.value) {


                        const leadQuetionObj = (leadCollection?.questions).find((item) => {
                            return item.question_id == input?.id;
                        });

                        services?.push({
                            sender: "you",
                            answerType: 'Lead_Collection_Form',
                            question_id: leadQuetionObj?.question_id,
                            questionId: leadQuetionObj?.questionId,
                            roomKey: window.roomKey,
                            question: leadQuetionObj?.question,
                            answer: input?.value,
                            answerOption: "",
                            timeout: Date.now(),
                            referenceName: leadQuetionObj?.referenceName,
                            uuid: window.questionInfo?.uuid,
                            templateId: window?.questionInfo?.templateId,
                            tenantId: window?.questionInfo?.tenantId,
                            userUUID: window.questionInfo?.userUUID,
                            ideal: false,
                        });
                    }
                    const existingErrorMessage = input.parentNode.querySelector('.error-message');
                    // Remove any previous error message
                    if (existingErrorMessage) {
                        existingErrorMessage.remove();
                    }

                    if (hasInputBox && !input?.value) {
                        isValid = false;
                        input.classList.add('error');  // Add error class for styling
                        const errorMessage = document.createElement('span');
                        errorMessage.className = 'error-message';
                        errorMessage.textContent = "";
                        input.parentNode.appendChild(errorMessage);  // Append error message directly below the field
                    } else {
                        input.classList.remove('error');
                    }
                });
            }

            // Validate Radio Buttons
           const radioButtons = Array.from(window.shadow.querySelectorAll('.leadRadioType'));
            const answers = leadCollection?.questions?.filter((question)=> question.answerType === "Selectable_Option" )?.length;
            const selectedRadioButtons = radioButtons.filter(radio => radio.checked);
            
            const isRadioSelected = answers==selectedRadioButtons.length;
            console.log("isRadioSelected",isRadioSelected)
            const radioSection = window.shadow.querySelector('.cbw__receiver-msg'); // Parent container for radio buttons
            radioButtons.forEach((radio) => {
            const inputElement = window.shadow.querySelector('.leadRadioType');

            const dataId = inputElement.getAttribute('data-id');
              if (radio.checked) {
                const leadQuetionObj = (leadCollection?.questions).find((item) => {
                            return item.question_id == dataId;
                        });

                        services?.push({
                            sender: "you",
                            answerType: 'Lead_Collection_Form',
                            question_id: leadQuetionObj?.question_id,
                            questionId: leadQuetionObj?.questionId,
                            roomKey: window.roomKey,
                            question: leadQuetionObj?.question,
                            answer: radio?.value,
                            answerOption: "",
                            timeout: Date.now(),
                            referenceName: leadQuetionObj?.referenceName,
                            uuid: window.questionInfo?.uuid,
                            templateId: window?.questionInfo?.templateId,
                            tenantId: window?.questionInfo?.tenantId,
                            userUUID: window.questionInfo?.userUUID,
                            ideal: false,
                        });

                console.log("message ", radio.checked);
              }
            });
            if (hasSelect && !isRadioSelected) {
                isValid = false;
                const existingErrorMessage = radioSection.querySelector('.error-message');
                // Remove any previous error message
                if (existingErrorMessage) {
                    existingErrorMessage.remove();
                }

                const errorMessage = document.createElement('span');
                errorMessage.className = 'error-message';
                errorMessage.textContent = '';
                radioSection.appendChild(errorMessage);  // Append error message below the radio section
            } else {
                // Remove previous error message if any
                const existingErrorMessage = radioSection.querySelector('.error-message');
                if (existingErrorMessage) {
                    existingErrorMessage.remove();
                }
            }

            // Validate Dropdowns (Searchable Dropdown)
            const dropdowns = window.shadow.querySelectorAll('.lead-select');
            dropdowns.forEach((dropdown) => {
                const existingErrorMessage = dropdown.parentNode.querySelector('.error-message');
                // Remove any previous error message
                if (existingErrorMessage) {
                    existingErrorMessage.remove();
                }

                if (hasRadio && !dropdown.value) {
                    isValid = false;
                    dropdown.classList.add('error');
                    const errorMessage = document.createElement('span');
                    errorMessage.className = 'error-message';
                    errorMessage.textContent = '';
                    dropdown.parentNode.appendChild(errorMessage);  // Append error message below the dropdown field
                } else {
                    dropdown.classList.remove('error');
                }
            });

            // If form is not valid, stop form submission
            if (!isValid) {
                 validation = "Please fill in all required fields."
                 displayErrorMassage();
                return;
            }
            console.log("123456543",{answer: services, question_id: '', sender: 'you', uuid: window.questionInfo?.uuid,answerType:'Lead_Collection_Form'})
            // Proceed with sending the data if validation passes
            const name = window.shadow.getElementById('input_name')?.value || "";
            const selectedRadio = window.shadow.querySelector('input[name="optionRadio1"]:checked');
            const selectable = selectedRadio ? selectedRadio.nextElementSibling?.textContent.trim() : "";
            const serviceSelects = window.shadow.querySelectorAll('[id^="serviceSelect_"]');

            serviceSelects.forEach(select => {
            const inputElement = window.shadow.querySelector('.lead-select');

            const dataId = inputElement.getAttribute('data-id');
            const selectedValue = select.value;
            const leadQuetionObj = (leadCollection?.questions).find((item) => {
                            return item.question_id == dataId;
                        });

                        services?.push({
                            sender: "you",
                            answerType: 'Lead_Collection_Form',
                            question_id: leadQuetionObj?.question_id,
                            questionId: leadQuetionObj?.questionId,
                            roomKey: window.roomKey,
                            question: leadQuetionObj?.question,
                            answer: select?.value,
                            answerOption: "",
                            timeout: Date.now(),
                            referenceName: leadQuetionObj?.referenceName,
                            uuid: window.questionInfo?.uuid,
                            templateId: window?.questionInfo?.templateId,
                            tenantId: window?.questionInfo?.tenantId,
                            userUUID: window.questionInfo?.userUUID,
                            ideal: false,
                        });
            });

            const formData = {
                name,
                services,
                selectable,
            };

            ws.send(
              JSON.stringify({
                answer: services,
                answerType: 'Lead_Collection_Form',
                question_id: "",
                sender: "you",
                uuid: leadCollection?.userUUID
              })
            );

            console.log("formData", formData);
            localStorage.setItem('contactFormData', JSON.stringify(formData));

            // Hide the form after submission
            const leadFormSection = window.shadow.querySelector('.lead-form-section');
            if (leadFormSection) {
                leadFormSection.style.display = 'none'; 
            }

            const chatContainer = window.shadow.querySelector('.cbw__chat');
           
                const loaderId = 'main-loader-'+ window.loaderCount;
                window.shadow.getElementById(loaderId)?.classList?.add('hide');
                window.loaderCount = window.loaderCount + 1;
                loaderDisplay();
        });
    } else {
        console.error('Element with ID "form-lead-collection" not found.');
    }
}, 100);
}
return tempContainer;
}`;
window.shadow.appendChild(questionScript);

// document.addEventListener('dataEvent', (event) => {
//     window.portalAccess = event.detail;
//     console.log(window.portalAccess, 'window.portalAccess');
//     // Use data in your script
// });

const chatBotStyle = document.createElement("style");
chatBotStyle.innerHTML = `@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&family=Noto+Sans:ital,wght@0,100..900;1,100..900&display=swap');

:root {
    --cbw-header-background-color:   "#1264e2";
    --cbw-header-text-color:   "#ffffff";
    --cbw-header-color:   "#f0f0f0";
    --msg-input-color: #000;
    --cbw-bot-background-color:   "#e4e9f0";
    --cbw-bot-text-color:   "#161740";
    --cbw-header-background-logo-color:   "#f0f0f0";
    --cbw-sendmsg-text-color:   "#ffffff";
    --cbw-sendmsg-background-color:   "#1264e2";
    --cbw-logo-border-color:   "#ffffff";
    --cbw-send-btn-color:   "#1264e2";
    --cbw-font-style: "Montserrat"
    }
// <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Arial&family=Verdana&display=swap" rel="stylesheet">
.form-container {
      background-color: #e9edf7;
      padding: 20px 30px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      width: 374px;
      margin-left: 10px !important;
}
// .success-message {
//     background-color: #4CAF50; /* Green background */
//     color: white; /* White text */
//     padding: 10px;
//     margin-top: 20px;
//     border-radius: 5px;
//     text-align: center;
//     font-size: 16px;
// }
    .form-title{
        font-size: 16px;
        font-family: var(--cbw-font-style);
        font-weight: 600;
        margin-left: 12px;
        margin-bottom: 0px;
        color: var(--cbw-bot-text-color);
    }

    .errorMessageShow {
        color: red;
        font-size: 14px;
        font-family: var(--cbw-font-style);
        font-weight: 500;
        margin-bottom: 15px;
    }

     .input-lable{
        font-size: 14px;
        font-weight: 500;
        margin-left: 16px;
        font-family: var(--cbw-font-style);
        color: var(--cbw-bot-text-color);

      }
        .lead-input{
          margin-left:14px;
          font-size:14px;
        }
          .lead-radio{
           margin:0px !important;
          }
           .lead-select{
           width:66% !important;
           margin-left:16px !important;
           }
           .radio-lable{
           margin: 0px;
           }
.lead-form-section{
  background: var(--cbw-bot-background-color);
  padding: 10px;
  margin: 0px 20px 20px 20px;
  border-radius: 10px;
}
  }
    .form-lead-containt{
    font-size: 18px !important;
    color: #333 !important;
    margin-bottom: 15px !important;
    }
  .form-group {
    margin-bottom: 15px;
  }
  .form-group input, .form-group select {
      width: 85% !important;
        padding: 5px 15px;
        font-size: 14px;
        border: 1px solid #ccc;
        border-radius: 5px;
        outline: none;
        font-family: var(--cbw-font-style);
        background-color: #ffffff;
    }
    .form-group select{
        height: 40px;
    }

    .form-group input::placeholder, 
    .form-group input::-webkit-input-placeholder, 
    .form-group input:-ms-input-placeholder, 
    .form-group input:-moz-placeholder, 
    .form-group input::-moz-placeholder {
        font-family: var(--cbw-font-style) !important;
    }
      
    .form-group input:focus, .form-group select:focus {
      border-color: #007bff;
      box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
    }
    .form-group-radio {
    //   display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .form-group-radio label {
    //   display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      color: #555;
      cursor: pointer;
    }
    .form-group-radio input[type="radio"] {
      appearance: none;
      width: 18px;
      height: 18px;
      border: 2px solid #ccc;
      border-radius: 50%;
      display: inline-block;
      vertical-align: middle;
      outline: none;
      cursor: pointer;
    }
    .form-group-radio input[type="radio"]:checked {
      border-color: #4c2889;
      background-color: #4c2889;
    }
    .form-group-radio input[type="radio"]:checked::after {
      content: '';
      display: block;
      width: 8px;
      height: 8px;
      margin: 3px auto;
      background-color: white;
      border-radius: 50%;
    }
    .form-button {
      margin-top: 15px;
      margin-left: 16px;
        }
    .form-button button {
    //   color:  var(--calender-text-color);
    //   background:var(--calender-color);

        background: #ffffff;
        color: #1264E2;
      padding: 10px 20px;
      font-size: 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    // .form-button button:hover {
    //   background-color: #0056b3;
    // }
    // select {
    //   background-color: #fff;
    //   width:85%;
    //   margin-top:10px;
    // }
.cbw__bot-start-btn {
        position: fixed;
        bottom: 20px;
        cursor: pointer;
        z-index: 9999999998;
    }

    .cbw__bot-start-btn>img {
        width: 90px;
        max-width: 100%;
        height: auto;
    }

    .cbw__body:not(.show) {
        display: none;
    }
    .row-gap{
        row-gap: 16px;
    }
    .show{
        display:flex !important;
    }
    .cbw__body {
        all: unset;
        position: fixed;
        display: flex;
        line-height: 1.6;
        flex-direction: column;
        bottom: 20px;
        box-shadow: 0px 4px 20.4px 0px #00000817, 1px -2px 8px 1px #0000081f;
        border-radius: 20px;
        width: calc(100% - 60px);
        max-width: 350px;
        height: calc(100% - 120px);
        min-height: 250px;
        max-height: 480px;
        overflow: hidden;
        z-index: 999999999;
        background-color: #fff;
    }
    .chatbot-settings {
        all: unset;
        position: fixed;
        display: none;
        line-height: 1.6;
        flex-direction: column;
        bottom: 20px;
        box-shadow: 0px 4px 20.4px 0px #00000817, 1px -2px 8px 1px #0000081f;
        border-radius: 20px;
        width: calc(100% - 60px);
        max-width: 350px;
        height: calc(100% - 120px);
        min-height: 250px;
        max-height: 480px;
        overflow: hidden;
        z-index: 999999999;
        background-color: #fff;

        right: 520px;
    }
    .chatbot-settings {
            display:none;
            right: 520px;
            bottom:20px;
            }
    .select-items div {
        min-width: 120px;
        word-wrap: break-word;
    }

    .cbw__header {
        all:unset;
        font-family: var(--cbw-font-style);
        background-color: var(--cbw-header-background-color);
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 16px;
        background: var(--cbw-header-background-color); 
        color: var(--cbw-header-text-color);
    }
    .transform-div {
        transform: none !important;
    }
    .cbw-logo-box{
        height:35px;
        width:35px;
    }
        
    .cbw__assistant-icon {
        // background-color: #41c5fb;
        width: 100%;
        height: 100%;
        object-fit: contain;
        border-radius: 50rem;
    }

    .cbw__assistant-name {
        all: unset;
        line-height: 1;
        font-family: var(--cbw-font-style) !important;
        color: var(--cbw-header-text-color);
        font-size: 17px;
        margin: 0px !important;
        font-weight: 500 !important;
        overflow: hidden;
        margin-left: 10px !important;
        width: 190px;
    }
     
    .cbw__reset-btn svg{
        fill: var(--cbw-header-text-color);
    }
    .cbw__reset-btn {
        background-color: transparent;
        cursor: pointer;
        box-shadow: none;
        outline: none;
        border: none;
        padding: 8px;
        margin: 0;
        margin-left: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        color:inherit;
    }
    .cbw__reset-btn svg{
        fill: var(--cbw-header-text-color)
    }
    .cbw__close-btn {
        background-color: transparent;
        cursor: pointer;
        box-shadow: none;
        outline: none;
        border: none;
        padding: 8px;
        margin: 0;
        margin-left: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        color:inherit;
    }

    .cbw__footer {
        all:unset;
        position: relative;
        box-shadow: 0px -2px 0px 0px #D7DADD;
        margin-top: auto;
        width:100%;
        font-family: var(--cbw-font-style) !important;
    }
   
    //  11-11
     /* Header preview */

        .chatbot-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: #86CC27;
            padding: 10px;
            color: #000000;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .chatbot-header img {
            width: 30px;
            height: 30px;
        }

        .chatbot-header h1 {
            font-size: 20px;
            margin-left: 10px;
        }

        /* Chatbot Settings Container */
      
        .header-chat-setting{
        display:flex;
        padding:14px 20px;
        box-shadow: 0px 1px 4px 0px #00000040;

        }

        .chatbot-settings h2 {
            margin-bottom: 0px;
            font-size: 16px;
            color:#161740;
        }
        .setting_body{
            padding: 4px 20px;
            height: 370px;
            overflow-y: scroll;
            scrollbar-width: thin; /* For Firefox */
            scrollbar-color: #d0d0d0 #f0f0f0;
        }
            /* WebKit-based browsers (Chrome, Safari, Edge) */
            .setting_body::-webkit-scrollbar {
            width: 8px; /* Width of the scrollbar */
            }

            .setting_body::-webkit-scrollbar-thumb {
            background: linear-gradient(45deg, #6a11cb, #2575fc); /* Thumb color */
            border-radius: 10px; /* Rounded corners */
            }

            .setting_body::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(45deg, #2575fc, #6a11cb); /* Thumb color on hover */
            }

            .setting_body::-webkit-scrollbar-track {
            background: #eaeaea; /* Track color */
            border-radius: 10px; /* Rounded corners */
            }
        label {
            display: block;
            margin: 15px 0 5px;
            font-size: 14px;
        }

    .color-code,
    .file-name {
                font-size: 12px;
                color: #161740;
                padding-right:12px;
                font-weight:500;
            }
                
    .file-name {
        color: #555; 
        position:absolute;
        font-weight:600;
        padding:0 12px;
        }
    button#apply-btn,
    button#reset-btn {
                font-size:12px;
                border-radius: 3px;
                padding: 6px 12px;
                cursor: pointer;

        }
    button#reset-btn {
        background-color: #fff;
        margin-right: 10px;
        color: #999999;
        outline: none;
        border: 1px solid #999;
    }
    button#apply-btn {
        background: #1264e2;
        border: 1px solid #1264e2;
        color: #FFF;
        cursor: pointer;

    }
        button:hover {
            opacity: 0.9;
        }

     .setting_btn {
       position: fixed;
       top: 90%;
       transform: translateY(-50px);
       right:450px;
     }
      .setting_btn_back svg{
         animation: spin 2s linear infinite;
        }
         
       .setting_btn_back {
       background-color: #161740;
       padding: 8px 8px 5px 8px;
       border-top-left-radius: 10px; 
       border-bottom-left-radius: 10px;
        cursor:pointer;
       }
    // .cbw__input {
    //     

    //     height: 26px;    
    //     max-height: 150px; 
    //     overflow-y: auto; 
    //     padding: 10px;   
    //     resize: none;     /* Disable manual resizing (optional) */
    // }
    .cbw__input {
        all:unset;
        overflow-wrap: break-word;
        height: 48px; /* Initial height */
        max-height: 150px; /* Maximum height */
        min-height: 48px; /* Minimum height to start with */
        overflow-y: auto; /* Scrollbar for overflow */
        padding: 10px;
        resize: none; /* Disable manual resizing */
        box-sizing: border-box; /* Ensure padding is included in the height calculation */
        width: 100%; /* Full width for the textarea */
        font-family: var(--cbw-font-style) !important;
    }

    .loader-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(255, 255, 255, 0.8); /* Slightly transparent background */
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999; /* Make sure loader is on top of everything */
        transition: opacity 0.1s;
    }
    /* Loader styles */
    .loader-d {
        border: 5px solid #f3f3f3;
        border-top: 5px solid #3498db;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        animation: spin 1s linear infinite;
    }

    /* Loader animation */
        @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
   .cbw__input {
        width: 89% !important;
        background-color: #fff !important;
        display: block;
        outline: none !important;
        border: none !important;
        border-radius: 0 !important;
        padding: 10px 16px 10px 49px !important;
        font-size: 16px !important;
        line-height: unset !important;
    }
    // ::placeholder {
    
    //    font-size:14px !important;
    //    color:#333 !important;
    //    font-weight:bold !important;
    // }
    .cbw__input::placeholder { 
        font-size:14px !important;
        color:#999999 !important;
        font-weight:400 !important;
      }
   
    #messageInput {
       color:var(--msg-input-color) !important;
       font-weight:500 !important;
    }

    .cbw__attachement-btn {
        position: absolute;
        z-index: 1;
        outline: none !important;
        border: none !important;
        border-radius: 0 !important;
        margin: 0;
        padding: 0;
        top: 50%;
        left: 16px;
        transform: translateY(-50%);
        background-color: transparent;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color:var(--cbw-send-btn-color);
    }

    .cbw__send-btn {
        position: absolute;
        z-index: 1;
        outline: none !important;
        border: none !important;
        border-radius: 0 !important;
        margin: 0;
        padding: 0;
        right: 16px;
        top: 50%;
        transform: translateY(-50%);
        background-color: transparent;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color:var(--cbw-send-btn-color);
    }
    .wrapper-input {
        // display: flex;
        align-items: center;
        justify-content: center;
        position: relative
    }

    .cbw__chat_history {
        all: unset;
        // overflow: clip overlay; fix: scrollbar for each message
        display: -webkit-box;
        display: -webkit-flex;
        display: -ms-flexbox;
        display: flex;
        -webkit-flex-direction: column;
        -ms-flex-direction: column;
        flex-direction: column;
        row-gap: 10px;
        //NOTE: excessive padding while reopening chatbot
        // padding: 20px 0;
        // margin-bottom:20px;
    }

    .cbw__chat {
        all: unset;
        overflow: clip overlay;
        display: -webkit-box;
        display: -webkit-flex;
        display: -ms-flexbox;
        display: flex;
        -webkit-flex-direction: column;
        -ms-flex-direction: column;
        flex-direction: column;
        row-gap: 10px;
        padding: 20px 0;
        margin-bottom:20px;
    }

    /* width */
    .cbw__chat::-webkit-scrollbar {
        width: 8px;
    }

    /* Track */
    .cbw__chat::-webkit-scrollbar-track {
        background: transparent;
    }

    /* Handle */
    .cbw__chat::-webkit-scrollbar-thumb {
        background: #D7DADD;
        border-radius: 10px;
    }

    .cbw__receiver-msg-box,
    .cbw__sender-msg-box {
        font-family: var(--cbw-font-style) !important;
        position: relative;
        word-break: break-all;
    }

    .cbw__receiver-msg-box::before,
    .cbw__receiver-msg-box::after,
    .cbw__sender-msg-box::before,
    .cbw__sender-msg-box::after {
        position: absolute;
        content: '';
        width: 15px;
        height: 15px;
         border-radius: 0 0 20px 0;
        background-color:  var(--cbw-bot-background-color); ;
        z-index: 0;
        bottom: 2px;
        left: 8px;
    }

    .cbw__sender-msg-box::before,
    .cbw__sender-msg-box::after {
        background-color: var(--cbw-sendmsg-background-color);
        right: 9px;
        border-radius: 0 0 0px 20px;
        left: unset;
    }

    .cbw__receiver-msg-box::before,
    .cbw__sender-msg-box::before {
        background-color: #fff;
        z-index: 1;
        -webkit-transform: rotate(-30deg) translateX(-2px);
        -moz-transform: rotate(-30deg) translateX(-2px);
        -ms-transform: rotate(-30deg) translateX(-2px);
        transform: rotate(-30deg) translateX(-2px);
        transform-origin: left bottom;
        width: 20px;
        height: 20px;
    }

    .cbw__sender-msg-box::before {
        -webkit-transform: rotate(30deg) translateX(2px);
        -moz-transform: rotate(30deg) translateX(2px);
        -ms-transform: rotate(30deg) translateX(2px);
        transform: rotate(30deg) translateX(2px);
        transform-origin: right bottom;
    }

    .cbw__sender-file-msg-box {
        font-family: var(--cbw-font-style) !important;
        position: relative;
        word-break: break-all;
    }

    // .cbw__sender-file-msg-box::before,
    // .cbw__sender-file-msg-box::after {
    //     position: absolute;
    //     content: '';
    //     width: 15px;
    //     height: 15px;
    //      border-radius: 0 0 20px 0;
    //     background-color:  red;
    //     // background-color:  var(--cbw-bot-background-color);
    //     z-index: 0;
    //     bottom: 2px;
    //     left: 8px;
    // }

    // .cbw__sender-file-msg-box::before,
    // .cbw__sender-file-msg-box::after {
    //     background-color: var(--cbw-sendmsg-background-color);
    //     right: 9px;
    //     border-radius: 0 0 0px 20px;
    //     left: unset;
    // }

    .cbw__sender-file-msg-box::before {
        background-color: #fff;
        z-index: 1;
        -webkit-transform: rotate(-30deg) translateX(-2px);
        -moz-transform: rotate(-30deg) translateX(-2px);
        -ms-transform: rotate(-30deg) translateX(-2px);
        transform: rotate(-30deg) translateX(-2px);
        transform-origin: left bottom;
        width: 20px;
        height: 20px;
    }

    .cbw__sender-file-msg-box::before {
        -webkit-transform: rotate(30deg) translateX(2px);
        -moz-transform: rotate(30deg) translateX(2px);
        -ms-transform: rotate(30deg) translateX(2px);
        transform: rotate(30deg) translateX(2px);
        transform-origin: right bottom;
    }

    .spinner {
        border: 16px solid #f3f3f3;
        border-top: 16px solid #3498db;
        border-radius: 50%;
        width: 120px;
        height: 120px;
        animation: spin 2s linear infinite;
    }
      
      /* Keyframes for the spinner animation */
      @keyframes spin {
        0% { transform: rotate(0deg); }  /* Initial state */
        100% { transform: rotate(360deg); }  /* Full rotation */
      }

    .cbw__receiver-msg,
      .cbw__sender-msg-box>.cbw__sender-msg {
        word-wrap: break-word !important; 
        overflow-wrap: break-word !important; 
        word-break: keep-all !important; 
        background-color: var(--cbw-bot-background-color);
        width: -webkit-fit-content;
        width: -moz-fit-content;
        width: fit-content;
        max-width: 83%;
        margin: 0;
        margin-left: 16px;  
        color: var( --cbw-bot-text-color);
        border-radius: 8px;
        z-index: 2;
        position: relative;
        padding: 3px 14px;
        font-size: 14px;
        font-weight: 500;
        min-height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        word-break: break-all;
  }

   .cbw__sender-msg-box > .cbw__sender-msg {
    background-color: var(--cbw-sendmsg-background-color); 
    max-width: 65%;
    margin: 0;
    margin-left: auto;
    margin-right: 16px;
    color: var(--cbw-sendmsg-text-color);  
}


.cbw__sender-file-msg-box>.cbw__sender-file-msg {
    word-wrap: break-word !important; 
    overflow-wrap: break-word !important; 
    word-break: keep-all !important; 
    background-color: var(--cbw-bot-background-color);
    width: -webkit-fit-content;
    width: -moz-fit-content;
    width: fit-content;
    max-width: 83%;
    margin: 0;
    margin-left: 16px;  
    color: var( --cbw-bot-text-color);
    border-radius: 8px;
    z-index: 2;
    position: relative;
    padding: 3px 14px;
    font-size: 14px;
    font-weight: 500;
    min-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    word-break: break-all;
}

.cbw__sender-file-msg-box > .cbw__sender-file-msg {
background-color: #F7F5F5; 
max-width: 65%;
margin: 0;
margin-left: auto;
margin-right: 16px;
color: var(--cbw-sendmsg-background-color);  
}


    [data-type="receiver-msg-select"].cbw__receiver-msg-box>.cbw__receiver-msg {
       
        background-color: var(--cbw-bot-background-color);
        color: var( --cbw-bot-text-color);
        gap: 16px;
        cursor: pointer;
    }

    .loader {
        display: block;
        width: 8px;
        aspect-ratio: 1;
        border-radius: 50%;
        animation: l5 2s infinite linear alternate;
        margin: 0 16px;
    }

    [data-type="sender-msg-loader"] .loader {
        animation-name: l5-light;
    }

    @keyframes l5 {
        0% {
            box-shadow: 12px 0 #999, -12px 0 #9992;
            background: #999
        }

        33% {
            box-shadow: 12px 0 #999, -12px 0 #9992;
            background: #9992
        }

        66% {
            box-shadow: 12px 0 #9992, -12px 0 #999;
            background: #9992
        }

        100% {
            box-shadow: 12px 0 #9992, -12px 0 #999;
            background: #999
        }
    }

    @keyframes l5-light {
        0% {
            box-shadow: 12px 0 #fff, -12px 0 #fff2;
            background: #fff
        }

        33% {
            box-shadow: 12px 0 #fff, -12px 0 #fff2;
            background: #fff2;
        }

        66% {
            box-shadow: 12px 0 #fff2, -12px 0 #fff;
            background: #fff2;
        }

        100% {
            box-shadow: 12px 0 #fff2, -12px 0 #fff;
            background: #fff;
        }
    }

    .cbw__receiver-msg-option-box>.cbw__option-box,
    .cbw__receiver-msg-multi-option-box>.cbw__option-box {
        margin-top: 10px;
        margin-left: 16px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
        max-width: 85%;
    }

    .cbw__receiver-msg-multi-option-box>.cbw__option-box {
        max-width: unset;
    }

    .cbw__receiver-msg-option-box>.cbw__option-box .cbw__btn-check+.cbw__btn-check-label {
        cursor: pointer;
        display: inline-block;
        border-radius: 10px;
        padding: 10px 16px;
        font-size: 16px;
        font-weight: 600;
        color: var(--cbw-header-background-color);
        background-color: #F7F5F5;
        box-shadow: 0px 1px 0px 0px #BEC4CE;
    }

    .cbw__receiver-msg-option-box>.cbw__option-box .cbw__btn-check:checked+.cbw__btn-check-label {
        color: #999;
        pointer-events: none;
    }

    .cbw__receiver-msg-option-box>.cbw__option-box .cbw__btn-check:disabled+.cbw__btn-check-label {
        opacity: 0.7;
        pointer-events: none;
    }

    .cbw__receiver-msg-multi-option-box>.cbw__option-box .cbw__btn-check+.cbw__btn-check-label {
        cursor: pointer;
        display: inline-block;
        border-radius: 10px;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: 600;
        color: var(--cbw-header-background-color);
        border: 1.5px solid var(--cbw-header-background-color);
    }

    .cbw__receiver-msg-multi-option-box>.cbw__option-box .cbw__btn-check:checked+.cbw__btn-check-label {
        color: #fff;
        background-color: var(--cbw-header-background-color);
        pointer-events: none;
    }

    .cbw__receiver-msg-multi-option-box>.cbw__option-box .cbw__btn-check:disabled+.cbw__btn-check-label {
        opacity: 0.7;
        pointer-events: none;
    }

    .cbw__receiver-msg-search-box>.cbw__search-box {
        position: relative;
        margin-left: 16px;
        max-width: 70%;
    }

    .cbw__receiver-msg-search-box>.cbw__search-box svg {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: 10px;
    }

    .cbw__receiver-msg-search-box > .cbw__search-box .cbw__search-city {
        padding: 12px 12px 12px 35px;
        border: 1.5px solid var(--cbw-header-background-color);
        border-radius: 10px;
        font-size: 16px;
        display: block;
        width: 100%;
    }

    /* Marked js changes fully ai */
    .cbw__receiver-msg pre{
        all: unset !important;
        max-width: 100% !important;
        white-space: break-spaces;
        text-align: start !important;
        font-family: var(--cbw-font-style) !important;
        padding: 0px 10px !important;
    }

    [data-type="receiver-msg-option-list"].cbw__receiver-msg-box>.cbw__receiver-msg {
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        padding:10px 12px;
        min-width:140px;
        max-width: 200px;
    }
    #error {
        height: 100vh;
        display: flex;
        flex-direction: column-reverse;
        margin-bottom: 0;
    }

    .cbw__option-list-box {
        font-family: var(--cbw-font-style);
        display: flex;
        flex-direction: column;
        gap: 10px;
        padding-top: 10px;
        width: 100%;
        overflow-y:auto;
        overflow-x:clip;
    }
       

    .cbw__option-list-box>.cbw__option-list-radio>input[type="radio"]+label {
        word-wrap: break-word !important; 
        overflow-wrap: break-word !important; 
        // word-break: keep-all !important; 
        cursor: pointer;
        position: relative;
        display: inline-block;
        padding: 10px;
        display: flex;
        font-size: 14px;
        align-items: center;
        gap: 6px;
        border-radius: 6px;
        background-color: #FFFFFF8F;
        font-weight: 500;
        margin-top: 0px !important;
    }

.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7); /* Dark background with opacity */
    display: none; /* Initially hidden */
    z-index: 999999999; /* Ensure overlay is on top */
    
}

    .popup {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 20px 10px 20px 20px;
    z-index: 9999999999;
    width:600px;
    border-radius: 10px;
}
   .chatContent{
    font-size: 14px;
    font-weight: 600;
    }
    .btns{
    justify-content: flex-end;
    display: flex;
    }
    .heder_btn_space{
      display:flex;
      justify-contant:space-between
    }
    .popupButton{
    background-color: #1264e2;
    padding: 7px 20px 7px 20px;
    border-color: #1264e2;
    color: white;
    border-radius: 3px;
    margin-top:30px;
    border:none;
    }
    .popupNoButton{
    background-color: #1264e2;
    padding: 7px 20px 7px 20px;
    border-color: #1264e2;
    color: white;
    border-radius: 3px;
    margin-top:30px;
    border:none;
    margin-right:10px
    }
    .cbw__option-list-box>.cbw__option-list-radio>input[type="radio"]+label::before {
      all:unset;
        content: "";
        width: 20px;
        min-width:20px !important;
        height: 20px;
        border: 1px solid #D7DADD;
        border-radius: 50rem;
        background: #fff;
        box-shadow: 0px 1px 0px 0px var(--cbw-bot-background-color);
    }

    .cbw__option-list-box>.cbw__option-list-radio>input[type="radio"]:checked+label::before {
        // all:unset;
        border-color: var( --cbw-bot-text-color);
        background: url("data:image/svg+xml,%3Csvg height='10' viewBox='0 0 13 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1.98047 6.46812L4.83929 9.74276L11.9863 1.55615' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A") no-repeat center, linear-gradient(0deg, #161740, #161740);
    }
    .hide {
        display: none !important;
    }
    .calendly-btn {
        font-size: 15px;
        background: var(--cbw-bot-background-color);
        /* background: grey; */
        color: blue;;
        border: 0px;
        cursor:pointer;
        font-weight: 600;
        border-bottom: 1px solid blue;
    }
    .calendly-back-btn-style{
        word-wrap: break-word !important; 
        overflow-wrap: break-word !important; 
        word-break: keep-all !important; 
        background-color: var(--calender-color);
        width: -webkit-fit-content;
        width: -moz-fit-content;
        width: fit-content;
        max-width: 83%;
        margin: 0;
        margin-left: 16px;  
        color: var( --calender-color);
        border-radius: 8px;
        z-index: 2;
        position: relative;
        padding: 3px 14px;
        font-size: 13px;
        font-weight: 500;
        min-height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        word-break: break-all;
        }
    .calendly-text-style {
    font-size: 15px;
    background: var(--calender-color);
    /* background: grey; */
    color: var(--calender-text-color);
    border: 0px;
    cursor: pointer;
    font-weight: 600;
    border-bottom: 1px solid var(--calender-text-color);
    }
    .calendly-container {
        width: 100% !important;
        // height: 300px !important;
    }
    .custom-select {
        /* all:unset; */
        position: relative;
        font-family: var(--cbw-font-style);
        padding-left: 16px;
        width: 55%;
    }
      
    .custom-select select {
        display: none; /*hide original SELECT element: */
    }
      
    .select-selected {
        background-color: white;
        color: black !important;
        text-transform: capitalize;
        border:1px solid #D7DADD !important;
        border-radius:4px !important;
        box-shadow: 0px 4px 5px 0px #0000;
        font-size: 13px;
    }
      
    /* Style the arrow inside the select element: */
    .select-selected:after {
        position: absolute;
        content: "";
        top: 18px;
        right: 10px;
        width: 0;
        height: 0;
        border: 6px solid transparent;
        border-color: #878F95 transparent transparent transparent;
    }
      
    /* Point the arrow upwards when the select box is open (active): */
    .select-selected.select-arrow-active:after {
        border-color: transparent transparent #878F95 transparent;
        top: 7px;
    }
      
    /* style the items (options), including the selected item: */
    .select-items div,.select-selected {
        padding: 8px 16px;
        border: 1px solid transparent;
        // border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
        cursor: pointer;
    }
    .select-items div{
        margin:5px;
    }
    /* Style items (options): */
    .select-items {
        position: absolute;
        background-color: white;
        color: black !important;
        top: 100%;
        left: 16px;
        right: 0;
        z-index: 99;
        text-transform: capitalize;
        border:1px solid #D7DADD;
        border-radius:4px;
        margin-bottom:10px !important;
        box-shadow: 0px 4px 5px 0px var(--cbw-bot-background-color);
    }

    .select-items{
        max-height:150px !important;
        overflow-y:scroll !important;
        font-size: 13px;
    }

    /* Custom scrollbar styling (optional) */
    /* General scrollbar styling for all elements with custom scrollbars */

    .custom-scrollbar::-webkit-scrollbar {
        width: 8px; /* Set the width of the scrollbar */
    }
    .custom-scrollbar::-webkit-scrollbar-track {
        background: #f1f1f1; /* Background color of the scrollbar track */
    }
    .custom-scrollbar::-webkit-scrollbar-thumb {
        background: #888; /* Color of the scrollbar thumb */
        border-radius: 4px; /* Rounded corners for the scrollbar thumb */
    }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover {
        background: #555; /* Hover state color for the scrollbar thumb */
    }

    .select-items::-webkit-scrollbar {    
        width: 8px;
    }
    .select-items::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    .select-items::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }
    .select-items::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
    .calendly-wrapper {
        padding: 20px !important;
        background-color: #f9f9f9;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
      
    .select-hide {
        display: none;
    }
      
    .select-items div:hover, .same-as-selected {
        background-color: #E4E9F0;
        border-radius:4px;
    }
    dropdown-option-btn {
        text-transform: capitalize;
    }
    .text-capitalize {
        text-transform: capitalize;
    }
    .pointer-event {
        pointer-events: none !important;
    }
    .cbw__error {
        // margin-bottom: 5px;
        // padding-left: 14px;
        font-size: 12px;
        color: red;
        background: #FF173333;
        padding: 5px 18px;
    }

    .accordion-container {
        position: relative;
        border-bottom: 1px solid #D7DADD;
        background-color: white;
    }
    
    .cbw__accordion {
        font-family: var(--cbw-font-style);
        cursor: pointer;
        padding: 3px 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #EEEFF1
    }

    .cbw__accordion-title {
        font-size: 14px;
        color: #333;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .cbw__accordion-icon {
        display: flex;
        align-items: center;
    }

    .cbw__accordion-arrow {
        transition: transform 0.3s ease;
    }

    .cbw__accordion-arrow.open {
        transform: rotate(90deg);
    }

    .cbw__accordion-content {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease, padding 0.3s ease, opacity 0.3s ease;
        padding: 0 16px;
        left: 0;
        right: 0;
        background-color: #EEEFF1;\
        opacity: 0;
        z-index: 10;
    }

    .cbw__accordion-content.open {
        max-height: 160px;
        opacity: 1;
    }

    .cbw__accordion-text {
        font-size: 13px;
        color: #666;
        line-height: 1.5;
        margin-top: 0
    }    

    .setting-pair {
        display: flex;
        justify-content: space-between;
        align-items: center; 
        margin-bottom:8px;
    }

   .setting-buttons {
    display: flex;
    position: sticky;
    bottom: -14px;
    padding: 10px 0px 35px 20px;
    background: #fff;
    width: 100%;
    left: 0;
    right: 0;
}

    .setting-pair label {
        margin: 0;
        font-weight: 600;
        width: 40%;
        font-size:12px;
        color: #161740;
        margin-right: 10px;
    }
        input[type="color"], input[type="file"] {
        margin-left: 10px;
        border: 0;
        outline: 0;
        box-shadow: none;
        background: transparent;
        width:80px;
        height:24px;
        -webkit-appearance: none;
        border: none;
    }

    .setting-input-container {
        width: 190px;
    }

    .setting-pair div {
        display: flex;
        align-items: center;
        border: 1px solid #cccccc;
        width: 160px;
        border-radius: 4px;
        padding: 4px 0;
        justify-content: space-between;
    }
        input[type="file"] {
        opacity: 0;
        width: 100%;
        z-index: 1;
        position: relative;
        cursor: pointer;
    }


    .up_img svg {
        height: 20px;
        width: 14px;
        padding-top: 3px;
    }

    .cbw__receiver-msg-multi-option-box > .cbw__option-box .cbw__btn-check + .cbw__btn-check-label {
        cursor: pointer;
        display: inline-block;
        border-radius: 10px;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: 600;
        color: var(--cbw-header-background-color);
        border: 1.5px solid var:#1264E2; 
    }

    .cbw__receiver-msg-multi-option-box > .cbw__option-box .cbw__btn-check:checked + .cbw__btn-check-label {
        color: var(--white-color); 
        background-color: var(--cbw-header-background-color);
        pointer-events: none; 
    }

    .css-1bzq5d0 {
    position: fixed;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    -webkit-box-pack: center;
    justify-content: center;
    inset: 0px;
    -webkit-tap-highlight-color: transparent;
    background-color: rgba(0, 0, 0, 0.35);
    z-index: -1;
}

    .cbw__receiver-msg-search-box > .cbw__search-box .cbw__search-city {
        padding: 12px 12px 12px 35px;
        border: 1.5px solid var(--cbw-header-background-color); 
        border-radius: 10px;
        font-size: 16px;
        display: block;
        width: 100%;
    }


  span.up_img {
    background: #1264E2;
    border-radius: 4px;
    padding: 1px 10px;
    position: absolute;
    right: 0px;
    line-height: 24px;
}
    .header_logo_bg{
        height:40px;
        width:40px;
        background: var(--cbw-header-background-logo-color); 
        border-radius:50%;
        display:flex;
        justify-content: center;
        align-items: center;
    }
    .position-relative{
        position:relative;
    }
    .setting-input-container {
            display: flex;
            align-items: center;
            gap: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            max-width: 250px;
            background-color: #fff;
            }

    select#font-dropdown {
        background: transparent;
        border: 0;
        width: 100%;
        height: 24px;
        padding: 0 10px;
    }
    :focus-visible {
       outline: -webkit-focus-ring-color auto 0px;
    }
   .main-logo-priview-box {
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background: var(--cbw-logo-border-color);
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0;
}
   .main-logo {
    height: 60px;
    width: 60px;
    overflow: hidden;
    border-radius: 50%;
}

   .main-logo img{
        height:100%;
        width:100%;
        object-fit:contain;
   }
        /* Snackbar styling */
/* Snackbar styling */
#snackbar {
  visibility: hidden; /* Hidden by default */
  min-width: 250px; /* Minimum width of snackbar */
  background-color: green; /* Snackbar background color */
  color: #fff; /* Text color */
  text-align: center; /* Center align the text */
  border-radius: 2px; /* Rounded corners */
  padding: 16px; /* Padding for the snackbar */
  position: fixed; /* Fixed position at the top-right */
  z-index: 99999999999; /* Appear above all other content */
  right: 30px; /* 30px from the right edge */
  top: 30px; /* 30px from the top edge */
  font-size: 17px; /* Font size */
}

/* Add 'show' class to display the snackbar with animation */
#snackbar.show {
  visibility: visible; /* Make it visible */
  animation: fadein 0.5s, fadeout 0.5s 3s; /* Show and hide animation */
}

/* Animation for fade-in from the top */
@keyframes fadein {
  from {
    top: -50px; /* Start from above the viewport */
    opacity: 0;
  }
  to {
    top: 30px; /* Final position at 30px from the top */
    opacity: 1;
  }
}

/* Animation for fade-out after a delay */
@keyframes fadeout {
  from {
    top: 30px; /* Start at the final position */
    opacity: 1;
  }
  to {
    top: -50px; /* Move upwards, out of view */
    opacity: 0;
  }
}

    `;
const chatbotBody = document.createElement("div");
chatbotBody.className = "cbw__body";
chatbotBody.innerHTML = `<!-- Header :: Start -->
    <div class="cbw__header">
        <div class="header_logo_bg">
            <div class="cbw-logo-box">
                <img id="headerLogo" class="cbw__assistant-icon" src="${window.defaultLogo}" alt="assistant-icon">
            </div>
       </div>
        <span class="cbw__assistant-name"  style="padding:0">AI Assistant</span>

        <button class="cbw__reset-btn" id="btn-reset" tabindex="0" type="button">
           <svg width="26" height="22" viewBox="0 0 26 22" fill="none" xmlns="http://www.w3.org/2000/svg">
           <path d="M4.85007 11V13.0313L2.83006 10.928C2.72745 10.8137 2.60298 10.7211 2.46399 10.6557C2.32416 10.5899 2.17249 10.553 2.01806 10.5471C1.86363 10.5412 1.7096 10.5665 1.56518 10.6215C1.42075 10.6765 1.28888 10.7601 1.17746 10.8671C1.06604 10.9742 0.977348 11.1027 0.916681 11.2448C0.856014 11.387 0.824617 11.5399 0.824367 11.6944C0.824116 11.849 0.855018 12.002 0.915224 12.1443C0.975058 12.2857 1.06261 12.4138 1.17272 12.5208L5.17086 16.6859L5.17092 16.6859C5.27823 16.7976 5.40699 16.8864 5.54947 16.9471C5.69195 17.0078 5.84521 17.0391 6.00007 17.0391C6.15494 17.0391 6.3082 17.0078 6.45068 16.9471C6.59316 16.8864 6.72192 16.7976 6.82923 16.6859L6.82929 16.6859L10.828 12.5202C10.9363 12.4125 11.0221 12.2843 11.0803 12.143C11.1388 12.0012 11.1683 11.8491 11.167 11.6957C11.1658 11.5423 11.134 11.3907 11.0733 11.2499C11.0126 11.109 10.9243 10.9817 10.8137 10.8754C10.7031 10.7691 10.5723 10.6861 10.4291 10.6311C10.2859 10.5762 10.1331 10.5504 9.97979 10.5554C9.82647 10.5604 9.6757 10.596 9.53635 10.6601C9.39757 10.724 9.27291 10.8148 9.16965 10.9274L7.15007 13.0311V11C7.15007 8.91805 7.97713 6.92137 9.44929 5.44921C10.9214 3.97705 12.9181 3.15 15.0001 3.15C17.082 3.15 19.0787 3.97705 20.5509 5.44921C22.023 6.92137 22.8501 8.91805 22.8501 11C22.8501 13.0819 22.023 15.0786 20.5509 16.5508C19.0787 18.0229 17.082 18.85 15.0001 18.85H14.5001C14.1951 18.85 13.9026 18.9712 13.6869 19.1868C13.4712 19.4025 13.3501 19.695 13.3501 20C13.3501 20.305 13.4712 20.5975 13.6869 20.8132C13.9026 21.0288 14.1951 21.15 14.5001 21.15H15.0001C20.6059 21.15 25.1501 16.6058 25.1501 11C25.1501 5.39416 20.6059 0.85 15.0001 0.85C9.39423 0.85 4.85007 5.39416 4.85007 11Z" fill= var(--header-font-color) stroke= var(--header-font-color) stroke-width="0.3"/>
           </svg>
        </button>

        <button class="cbw__close-btn" tabindex="0" type="button">
            <svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12.9902 2.39661L1.51172 13.8751" stroke="currentcolor" stroke-width="3" stroke-linecap="round"
                    stroke-linejoin="round" />
                <path d="M1.51172 2.39661L12.9902 13.8751" stroke="currentcolor" stroke-width="3" stroke-linecap="round"
                    stroke-linejoin="round" />
            </svg>
        </button>
    </div>
    <!-- Header :: End -->`;
const cbwChatCalendar = document.createElement("div");
cbwChatCalendar.className = "cbw__chat__calendar";
// cbwChatCalendar.id = "chat-container";
cbwChatCalendar.style.overflowY = "clip overlay;";
cbwChatCalendar.style.height = "calc(100% - 60px)";
cbwChatCalendar.style.overflowY = "scroll";
cbwChatCalendar.style.display = "none";
chatbotBody.appendChild(cbwChatCalendar);
// starting of chat div
const cbwChat = document.createElement("div");
cbwChat.className = "cbw__chat";
cbwChat.id = "chat-container";

const chartFooter = document.createElement("div");
chartFooter.className = "cbw__footer hide";
chartFooter.innerHTML += `<!-- Footer :: Start -->


    <form class="cbw__footer">
        <div id="cbw__error" class="cbw__error hide"></div>

        <div class="accordion-container">
            <div class="cbw__accordion">
                <span class="cbw__accordion-title">
                    <span class="cbw__accordion-icon">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M8.86676 0.691778C8.77476 0.287156 8.41498 0 8 0C7.58502 0 7.22524 0.287156 7.13324 0.691778L6.31209 4.30307C6.08462 5.30342 5.30342 6.08462 4.30307 6.31209L0.691822 7.13324C0.287155 7.22524 0 7.58502 0 8C0 8.41498 0.287155 8.77476 0.691822 8.86676L4.30307 9.68791C5.30342 9.91538 6.08462 10.6966 6.31209 11.6969L7.13324 15.3082C7.22524 15.7128 7.58502 16 8 16C8.41498 16 8.77476 15.7128 8.86676 15.3082L9.68791 11.6969C9.91542 10.6966 10.6966 9.91538 11.6969 9.68791L15.3082 8.86676C15.7128 8.77476 16 8.41498 16 8C16 7.58502 15.7128 7.22524 15.3082 7.13324L11.6969 6.31209C10.6966 6.08462 9.91542 5.30342 9.68791 4.30307L8.86676 0.691778Z" fill="#333"/>
                        </svg>
                    </span>
                    You are chatting with our assistant
                </span>
                <div class="cbw__accordion-arrow">
                    <svg width="8" height="13" viewBox="0 0 8 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M0 1.33672L4.96856 6.30528L0 11.2738L1.33672 12.6106L7.64201 6.30528L1.33672 0L0 1.33672Z" fill="#878F95"/>
                    </svg>
                </div>
            </div>
            <div class="cbw__accordion-content">
                <p class="cbw__accordion-text">
                    This chatbot provides general information and is not responsible for actions taken based on its responses. <a href="https://www.answeringlegal.com/privacy-policy" target="_blank" rel="noopener noreferrer">View Privacy Policy</a>.
                </p>
            </div>
        </div>

        <div class="wrapper-input">
        <input type="file" id="input__attachment" class="hidden" style="display: none;">
        <button class="cbw__attachement-btn">
            <svg width="20" height="22" viewBox="0 0 20 22" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M13.0595 5.39801L5.82206 12.954C5.62843 13.1562 5.47485 13.3961 5.37006 13.6603C5.26527 13.9244 5.21134 14.2074 5.21134 14.4933C5.21134 14.7792 5.26527 15.0623 5.37006 15.3264C5.47485 15.5905 5.62843 15.8305 5.82206 16.0326C6.01568 16.2347 6.24554 16.3951 6.49852 16.5045C6.7515 16.6139 7.02264 16.6702 7.29646 16.6702C7.57028 16.6702 7.84143 16.6139 8.09441 16.5045C8.34738 16.3951 8.57725 16.2347 8.77087 16.0326L15.9772 8.50917C16.3684 8.10071 16.6788 7.61579 16.8905 7.08211C17.1023 6.54843 17.2112 5.97643 17.2112 5.39877C17.2112 4.82111 17.1023 4.24911 16.8905 3.71543C16.6788 3.18175 16.3684 2.69683 15.9772 2.28837C15.187 1.46344 14.1153 1 12.9979 1C11.8804 1 10.8087 1.46344 10.0186 2.28837L2.84417 9.77839C2.2595 10.3888 1.79571 11.1134 1.47928 11.911C1.16286 12.7085 1 13.5633 1 14.4265C1 15.2898 1.16286 16.1446 1.47928 16.9421C1.79571 17.7396 2.2595 18.4643 2.84417 19.0747C3.42884 19.6851 4.12295 20.1693 4.88686 20.4996C5.65077 20.83 6.46953 21 7.29638 21C8.12324 21 8.94199 20.83 9.7059 20.4996C10.4698 20.1693 11.1639 19.6851 11.7486 19.0747L19 11.5042" stroke="#999999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        </button>
            <textarea aria-invalid="false" placeholder="Type here..." class="cbw__input custom-scrollbar" id="messageInput" rowindow.ws="4" cols="50"></textarea>
            <button class="cbw__send-btn">
                <svg width="22" height="22" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M22.3701 17.9461L24.6199 11.1969C26.5852 5.30094 27.5679 2.35295 26.0117 0.79681C24.4556 -0.759327 21.5076 0.223334 15.6116 2.18866L8.86246 4.43838C4.10383 6.02459 1.72452 6.81769 1.04839 7.98072C0.405176 9.08713 0.405176 10.4536 1.04839 11.56C1.72452 12.723 4.10383 13.5162 8.86245 15.1024C9.45219 15.2989 10.1157 15.1586 10.5573 14.7211L17.7734 7.57175C18.1794 7.16954 18.8346 7.17259 19.2368 7.57856C19.639 7.98454 19.6359 8.6397 19.23 9.04191L12.1303 16.0758C11.6436 16.558 11.4895 17.2961 11.7062 17.9461C13.2924 22.7047 14.0855 25.084 15.2485 25.7601C16.3549 26.4034 17.7214 26.4034 18.8278 25.7601C19.9908 25.084 20.7839 22.7047 22.3701 17.9461Z" fill="currentcolor"></path>
                </svg>
            </button>
        </div>
    </form>

    
    <!-- Footer :: End -->`;
chatbotBody.appendChild(cbwChat);
// const error = document.createElement('div');
// error.className= 'cbw__error';
// error.id= 'cbw__error';
// chatbotBody.appendChild(error);
chatbotBody.appendChild(chartFooter);

window.shadow.appendChild(chatBotStyle);
window.shadow.appendChild(chatbotBody);
const socketScript = document.createElement("script");
socketScript.innerHTML = ` 
    // socketCall('initial');

    
    function updateCSSVariable(variableName, value) {
        console.log("variableName ==========", variableName);
        console.log("value ==========", value);

        switch(variableName) {

            case '--cbw-header-background-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-header-text-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-header-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-bot-background-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-bot-text-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-header-background-logo-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-sendmsg-text-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-sendmsg-background-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-logo-border-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-send-btn-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case 'calender-box-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case 'calender-text-color':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case '--cbw-font-style':
                document.documentElement.style.setProperty(variableName, value);
                break;

            case "--msg-input-color":
                document.documentElement.style.setProperty(variableName, value);
                break;

            default:
                break;
        }
    }

    function startChatSafely() {
        // STATIC -- wait for static to be ready
        if (window.templateFormat === "static") {
            if (window.staticReady) {
                console.log("Static ready, starting chat");
                loadChat();
            } else {
                console.log("Static NOT ready yet, waiting");
                window.pendingStartChat = true;
            }
            return;
        }
        // DYNAMIC -- normal start
        loadChat();
    }

    function socketCall(type, brandingDetails, isConnectionExists = false) {

        console.log(brandingDetails);
        updateCSSVariable("--cbw-header-background-color", (brandingDetails?.headerColor != '' && brandingDetails?.headerColor !== undefined && brandingDetails?.headerColor !== null) ? brandingDetails?.headerColor : '#1264e2');
        updateCSSVariable("--cbw-header-text-color", (brandingDetails?.headerTextColor !== '' && brandingDetails?.headerTextColor !== undefined && brandingDetails?.headerTextColor !== null) ? brandingDetails?.headerTextColor : '#ffffff');
        updateCSSVariable("--cbw-header-color", (brandingDetails?.headerColor != '' && brandingDetails?.headerColor !== undefined && brandingDetails?.headerColor !== null) ? brandingDetails?.headerColor : '#f0f0f0');
        updateCSSVariable("--cbw-bot-background-color", (brandingDetails?.botMessageColor != '' && brandingDetails?.botMessageColor !== undefined && brandingDetails?.botMessageColor !== null) ? brandingDetails?.botMessageColor : '#e4e9f0');
        updateCSSVariable("--cbw-bot-text-color", (brandingDetails?.botTextColor != '' && brandingDetails?.botTextColor !== undefined && brandingDetails?.botTextColor !== null) ? brandingDetails?.botTextColor : '#161740');
        updateCSSVariable("--cbw-header-background-logo-color", (brandingDetails?.headerLogoBackground != '' && brandingDetails?.headerLogoBackground !== undefined && brandingDetails?.headerLogoBackground !== null) ? brandingDetails?.headerLogoBackground : '#f0f0f0');
        updateCSSVariable("--cbw-sendmsg-text-color", (brandingDetails?.userTextColor != '' && brandingDetails?.userTextColor !== undefined && brandingDetails?.userTextColor !== null) ? brandingDetails?.userTextColor : '#ffffff');
        updateCSSVariable("--cbw-sendmsg-background-color", (brandingDetails?.userMessageColor != '' && brandingDetails?.userMessageColor !== undefined && brandingDetails?.userMessageColor !== null) ? brandingDetails?.userMessageColor : '#1264e2');
        updateCSSVariable("--cbw-logo-border-color", (brandingDetails?.logoFillColor != '' && brandingDetails?.logoFillColor !== undefined && brandingDetails?.logoFillColor !== null) ? brandingDetails?.logoFillColor : '#ffffff');
        updateCSSVariable("--cbw-send-btn-color", (brandingDetails?.sendButtonColor != '' && brandingDetails?.sendButtonColor !== undefined && brandingDetails?.sendButtonColor !== null) ? brandingDetails?.sendButtonColor : '#1264e2');

        updateCSSVariable("calender-box-color", (brandingDetails?.sendButtonColor != '' && brandingDetails?.sendButtonColor !== undefined && brandingDetails?.sendButtonColor !== null) ? brandingDetails?.sendButtonColor : '#ffffff');
        updateCSSVariable("calender-text-color", (brandingDetails?.sendButtonColor != '' && brandingDetails?.sendButtonColor !== undefined && brandingDetails?.sendButtonColor !== null) ? brandingDetails?.sendButtonColor : '#ffffff');

        updateCSSVariable("--cbw-font-style", brandingDetails?.fontStyle || 'Montserrat');
        const headerImgElement = window.shadow.getElementById('headerLogo');
        headerImgElement.src = (!!brandingDetails && (brandingDetails?.headerLogoUrl !== undefined && brandingDetails?.headerLogoUrl !== null && brandingDetails?.headerLogoUrl !== '') ? brandingDetails?.headerLogoUrl : window.defaultLogo);

        updateCSSVariable("--msg-input-color", brandingDetails?.msgInputColor || "#000");

        setTimeout(() => {
            const mainImgElement = window.shadow.getElementById('mainLogo');
            mainImgElement.src = (!!brandingDetails && (brandingDetails?.mainLogoUrl !== undefined && brandingDetails?.mainLogoUrl !== null && brandingDetails?.mainLogoUrl !== '') ? brandingDetails?.mainLogoUrl : window.defaultLogo);
            // mainImgElement.src = (!!brandingDetails && (brandingDetails?.mainLogoUrl != '')  ? brandingDetails?.mainLogoUrl : window.defaultLogo);
        }, 1000);

        window.chatbotPosition = brandingDetails?.position || 'right';

        function browerTypes() {
            if (navigator.userAgent.indexOf("Chrome") != -1) {
                return 'Chrome';
            } else if (navigator.userAgent.indexOf("Safari") != -1) {
                return 'Safari';
            } else if (navigator.userAgent.indexOf("Firefox") != -1) {
                return 'Firefox';
            } else {
                return 'unknown';
            }
        }

        if(isConnectionExists) {
            const connectionStringSub = window.template_code + "++" + browerTypes() + "++" + isConnectionExists + "++" + window.userIP + "++" + window.templateFormat;
            window.ws = new WebSocket(window.socketPath, connectionStringSub);
            window.connectionLink.push(connectionStringSub);

            console.log("isConnectionExists  ::: ", connectionStringSub)
            console.log("isConnectionExists  ::: key", isConnectionExists)

            
        } else {

            let roomKey = generateUniqueCode();
            const connectionString = window.template_code + "++" + browerTypes() + "++" + roomKey + "++" + window.userIP + "++" + window.templateFormat;
            console.log("isConnectionExists  ::: new connection", connectionString)
            console.log("isConnectionExists  ::: new key", roomKey)
            window.ws = new WebSocket(window.socketPath, connectionString);
            window.connectionLink.push(connectionString);

            
        }

        window.ws.onopen = (event) => {
            event.preventDefault();

            if(type === 'initial') {
                const chatbotStartBtn = document.createElement('div');
                chatbotStartBtn.className ='cbw__bot-start-btn start-btn';
                    
                setTimeout(() => {
                    chatbotStartBtn.innerHTML =  \` <div class="main-logo-priview-box">
                            <div class="main-logo">  
                                <img id="mainLogo" src="${window.relatedPath}" alt="Chat Bot Image">
                            </div>
                    </div>\`;

                    const mainImgElement = window.shadow.getElementById('mainLogo');
                    mainImgElement.src = (!!brandingDetails && (brandingDetails?.mainLogoUrl !== undefined && brandingDetails?.mainLogoUrl !== null && brandingDetails?.mainLogoUrl !== '') ? brandingDetails?.mainLogoUrl : window.defaultLogo);
                    // mainImgElement.src = (!!brandingDetails && (brandingDetails?.mainLogoUrl != '')  ? brandingDetails?.mainLogoUrl : window.defaultLogo);
                }, 1000);

                window.shadow.appendChild(chatbotStartBtn);
                setTimeout(applyChatbotPosition, 0);

                // OPEN CHATBOT
                const chatbotStartBtn1 = window.shadow.querySelector(".cbw__bot-start-btn");
                const getChatbotOpened = localStorage.getItem('chatbotOpen');
                console.log(getChatbotOpened, 'getChatbotOpened')
                var cbwBody = window.shadow.querySelector(".cbw__body");

                const autoOpen = brandingDetails?.openOnStartup !== false; // fallback to true if undefined
                const closedBefore = localStorage.getItem("chatbotClosedManually") === "true";

                if ((autoOpen && !closedBefore) || getChatbotOpened === 'true') {

                    // OPEN THE CHAT
                    localStorage.setItem("chatbotOpen", "true"); 
                    localStorage.removeItem("chatbotClosedManually");

                    cbwBody.classList.add('show');
                    cbwBody.classList.remove('hide');
                    chatbotStartBtn1.classList.add('hide');
                    chatbotStartBtn1.classList.remove('show');

                    // ON DIALOG OPEN, DISPLAY ALL CONTENT
                    startChatSafely()
                } else {
                    console.log('in');
                    cbwBody.classList.add('hide');
                    cbwBody.classList.remove('show');
                    chatbotStartBtn1.classList.add('show');
                    chatbotStartBtn1.classList.remove('hide');
                }

                chatbotStartBtn.addEventListener("click", (event) => {
                    event.preventDefault();
                    clearInterval(window.intervalId);

                    // for chatnbot ui
                    localStorage.removeItem("chatbotClosedManually");
                    localStorage.setItem('chatbotOpen', true);
                    
                    // TIMER CHAGES
                    // window.timeCounter = 0;
                    // broadcastMessage(0, "timeCounter");
                    // localStorage.setItem("timeCounter", 0);

                    var cbwBody = window.shadow.querySelector(".cbw__body");
                    cbwBody.classList.add('show');
                    cbwBody.classList.remove('hide');

                    if(window.responseError === false) {
                        startChatSafely()
                    } else {
                        var botStartBtn = window.shadow.querySelector(".cbw__bot-start-btn");
                        botStartBtn.classList.add('hide');
                        botStartBtn.classList.remove('show');
                    }
                });
            
                var cbwCloseBtn = window.shadow.querySelector(".cbw__close-btn");
                var cbwBody = window.shadow.querySelector(".cbw__body");

                if(cbwCloseBtn && cbwBody) {
                    cbwCloseBtn.addEventListener("click", () => {

                        // clearInterval(window.intervalId);
                        // TIMER CHANGES
                        // window.timeCounter = 0;
                        // broadcastMessage(0, "timeCounter");
                        // localStorage.setItem("timeCounter", 0);
                        
                        // UI SHOW / HIDE
                        localStorage.setItem("isFirstLoaded", "hide");
                        localStorage.setItem('chatbotOpen', false);
                        localStorage.setItem("chatbotClosedManually", "true");

                        var botStartBtn = window.shadow.querySelector(".cbw__bot-start-btn")
                        botStartBtn.classList.add('show');
                        botStartBtn.classList.remove('hide');
                        cbwBody.classList.remove('show');
                        var inputBox = window.shadow.querySelector(".cbw__footer");
                        inputBox.classList.remove('show');
                        inputBox.classList.add('hide');
                        var messageInput = window.shadow.getElementById('messageInput');
                        messageInput.value = '' ;
                        messageInput.style.height =  '26px';
                        var cbwError = window.shadow.getElementById('cbw__error');
                        var sendBtn = window.shadow.querySelector('.cbw__send-btn');
                        cbwError.classList.remove('show');
                        cbwError.classList.add('hide');
                        sendBtn.classList.remove('transform-div');
                
                    });
                }
            } else {
                console.log("::: loadchat")
                startChatSafely();
            }
        };

        window.ws.onmessage = (event) => {

            // if(localStorage.getItem("isReset")) {
            //     if(document.visibilityState == 'hidden') {
            //         console.log("document.visibilityState", document.visibilityState);
            //         console.log("localstorage", localStorage.getItem("isReset"));
            //         window.ws.close();
            //     }
            // }



            const message = JSON.parse(event.data);
            window.questionInfo = message;

            // STATIC READY SIGNAL
            if (message?.responseType === "static_ready" && message?.templateFormat === "static") {
                console.log(" STATIC READY RECEIVED", message);

                window.staticReady = true;

                if (window.pendingStartChat) {
                    console.log(" Resuming pending static chat");
                    loadChat();
                    window.pendingStartChat = false;
                }
                return;
            }

            const loaderId = 'main-loader-'+ window.loaderCount;
            window.shadow.getElementById(loaderId)?.classList?.add('hide');

            // Remove disable state of input on receiving AI response
            const inputBox = window.shadow.getElementById('messageInput');
            
            if(inputBox){
                inputBox.style.cursor =  'text';
                inputBox.disabled = false;
                inputBox.focus();
            }

            // Remove disable state of file upload btn on receiving AI response
            const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
            
            if(fileUploadBtn){
                fileUploadBtn.style.cursor =  'pointer';
                fileUploadBtn.disabled = false;   
            }            

            console.log("kskugiweegfiwegfiugu",message);
            
            console.log("::: message?.answer", message?.answer);

            // save tenantId && templateId in local storage

            if (message?.tenantId && localStorage.getItem("tenantId") !== message.tenantId) {
                localStorage.setItem("tenantId", message.tenantId);
            }

            if (message?.templateId && localStorage.getItem("templateId") !== message.templateId) {
                localStorage.setItem("templateId", message.templateId);
            }            

            if(message?.message && (message?.responseType !== 'error') && (!message?.calendlyUrl)) {

                    let aiTempChat = window.shadow.querySelector('.cbw__chat');
                    let tempContainer = document.createElement('div');
                    tempContainer.className = 'cbw__receiver-msg-box';

                        // tempContainer.innerHTML += \` <div class="cbw__receiver-msg-box" id="">
                        //     <p class="cbw__receiver-msg">
                        //         \${message?.message}
                        //     </p>
                        // </div> \`;

                        let tempContainer_1 = document.createElement('div');
                            tempContainer_1.className = "cbw__receiver-msg-box";
                                let ptag_1 = document.createElement('span');
                                ptag_1.className = "cbw__receiver-msg";
                                ptag_1.innerHTML = \` <pre class="cbw__receiver-msg-pre">\${(window.marked && window.marked.parse)
                                    ? window.marked.parse(message?.message)
                                    : message?.message}</pre> \`;
                            tempContainer_1.append(ptag_1);
                        tempContainer.append(tempContainer_1);

                    setTimeout(scrollToBottom, 100);    
                    
                    aiTempChat.append(tempContainer);

                    appendMessageToLocalStorage(message);

                    // to trace session
                    setCurrentEpochTime()
                    setIntervalFunc();  

                    const inputBox = window.shadow.querySelector(".cbw__footer");
                    inputBox.classList.add('show');
                    inputBox.classList.remove('hide');

            // to populate message on all tab in AI like static
            } else if ((message?.chaType == "ai" || message?.answerType == 'file') && message?.sender === "you"){
                const chat = window.shadow.querySelector('.cbw__chat');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'cbw__sender-msg-box';
                messageDiv.dataset.type = 'sender-msg';
                let optionsHTML;

                if(message?.answerType === 'file'){
                 optionsHTML = prepareFileUploadMessage({
                        fileName: message?.fileName,
                        uploadStatus: "LOAD_FROM_HISTORY",
                        fileUrl: message?.fileUpload
                       });
                } else {
                 optionsHTML = \`
                    <div class="cbw__sender-msg">
                      <p>
                        \${message?.answer}
                      </p>
                    </div>
                \`;
                 }
                // let optionsHTML = \`
                //     <div class="cbw__sender-msg">
                //       <p>
                //         \${message?.answer}
                //       </p>
                //     </div>
                // \`;
                messageDiv.innerHTML = optionsHTML;

                setTimeout(scrollToBottom, 100);

                chat.appendChild(messageDiv);
                window.ws.send(JSON.stringify(messageInfo));
                window.loaderCount = window.loaderCount + 1;
                loaderDisplay();                     

            } else if(message?.message && (message?.responseType !== 'error') && message?.calendlyUrl !== '') {
            
                    console.log("message ::: ", message)

                    window.calendlyUrl = message?.calendlyUrl;
                    window.calendlyEmail = message?.calendlyEmail;
                    window.calendlyName = message?.calendlyName;

                    const chat = window.shadow.querySelector('.cbw__chat');
                        const calendlyId = "";
                        const tempContainerD = document.createElement('div');
                        tempContainerD.className = 'cbw__receiver-msg-box';
                        tempContainerD.innerHTML += \`
                        <div id="calendly-parentID">
                            <div class="cbw__receiver-msg">
                                <button class="calendly-btn" onclick="loadAiCalendly()" id="\${calendlyId}">
                                Choose Time
                                </button>
                            </div>
                        </div>
                        \`;
                    
                    setTimeout(scrollToBottom, 100);
                    chat.appendChild(tempContainerD);

                    // to trace session
                    setCurrentEpochTime()
                    setIntervalFunc(); 
                    
                    const inputBox = window.shadow.querySelector(".cbw__footer");
                    inputBox.classList.add('show');
                    inputBox.classList.remove('hide');

            } else if(message?.question_id) {
                if(message.sender == "you") {
                    let tempChat = window.shadow.querySelector('.cbw__chat');

                    // visibilityState for other tab to append html
                    if(message?.sender === 'you' && message?.answerType !== "Lead_Collection_Form" && document.visibilityState !== 'visible') {

                        if(Boolean(message?.answer) && message?.answerType === "File_Upload"){
                            let tempContainer = document.createElement('div');                         

                            tempContainer.innerHTML += \`
                            <div class="cbw__sender-file-msg-box" style="cursor: pointer;" onclick="window.open('\${message.answer}', '_blank')">
                                <div class="cbw__sender-file-msg">
                                    \${ellipsizeFilename(message.fileName)}
                                    <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-left: 10px">
                                        <path d="M1 13C1 15.8284 1 17.2426 1.87868 18.1213C2.75736 19 4.17157 19 7 19H13C15.8284 19 17.2426 19 18.1213 18.1213C19 17.2426 19 15.8284 19 13" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M10 1L10 14M10 14L6 9.625M10 14L14 9.625" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </div>
                            </div>
                            \`

                            tempChat.append(tempContainer);
                        } else if (message?.answer !== null && message?.answer !== undefined && message?.answerType !== "Calender") {
                            let tempContainer = document.createElement('div');
                            tempContainer.className = 'cbw__sender-msg-box';
                            tempContainer.innerHTML += \` <div class="cbw__sender-msg-box" id="">
                                <p class="cbw__sender-msg">
                                    \${message?.answer}
                                </p>
                            </div> \`;
                            tempChat.append(tempContainer);
                        } else if (message?.answerType === "Calender") {

                            let tempContainerCalendly = document.createElement('div');
                            tempContainerCalendly.style.position = 'relative';
                            tempContainerCalendly.className = 'cbw__receiver-msg-box pointer-event';
                            tempContainerCalendly.innerHTML += \` <p class="cbw__receiver-msg">
                                    \${message?.answer}
                                </p> \`;
                            tempChat.append(tempContainerCalendly);
                        }
                    }
                } else if(message.responseType == "chat_history") {
                    console.log("message.responseType ==========", message)
                } else {
                    // localStorage.setItem('chatData', JSON.stringify(message));

                    console.log("load ::: 3 else")
                    storeData(message);

                    nextQuestionPrepare(message); 
                }
            } else if(message?.answerType === "Lead_Collection_Form" && message.sender != "you") {
                console.log("::: Lead_Collection_Form");

                // localStorage.setItem('chatData', JSON.stringify(message));

                storeData(message);
                
                nextQuestionPrepare(message); 
            } else if(message?.responseType === "partial_chat" && message.sender != "you") {

                // TODO: fix for open chatbot after refresh

                const refreshedChat = window?.questionInfo?.chats;

                localStorage.setItem('chatData', JSON.stringify(refreshedChat));

                let tempChat = window.shadow.querySelector('.cbw__chat');
                    // visibilityState for other tab to append html

                    console.log("partial_chat ::: ", document.visibilityState);
                    if(document.visibilityState === 'visible' || document.visibilityState === 'hidden') {
                        (window?.questionInfo?.chats).forEach((item) => {    
                            if(item.answerType === 'Input_box') {
                                const boatMsg = document.createElement('div');
                                boatMsg.innerHTML += botTextMessages(item);
                                boatMsg.innerHTML += userTextMessages(item);
                                tempChat.append(boatMsg);
                            }
                            if(item.answerType === 'Selectable_Option') {
                                const boatMsg = document.createElement('div');
                                boatMsg.innerHTML += botRadioMessages(item);
                                boatMsg.innerHTML += userTextMessages(item);
                                tempChat.append(boatMsg);
                                
                            }
                            if(item.answerType === 'Searchable_Dropdown') {
                                const boatMsg = document.createElement('div');
                                boatMsg.innerHTML += botDropDownMessages(item);
                                boatMsg.innerHTML += userTextMessages(item);
                                tempChat.append(boatMsg);
                            }
                            if(item.answerType === "File_Upload"){
                                const boatMsg = document.createElement('div');
                                boatMsg.innerHTML += botTextMessages(item);
                                boatMsg.innerHTML += prepareFileUploadMessage({
                                                        fileName: 'item.fileName',
                                                        uploadStatus: "LOAD_FROM_HISTORY",
                                                        fileUrl: item.answer
                                                     });
                                tempChat.append(boatMsg)
                            }  
                        });
                    }
            } else if (message?.responseType === 'chat_history'){

                // fix: when multi chat refresh it repeats question
                // NOTE: api should return clean response
                function processRefreshedChatHistory(chatHistory) {
                    console.log("processRefreshedChatHistory arg", chatHistory)

                    if (!chatHistory || !Array.isArray(chatHistory) || chatHistory.length === 0) {
                        return [];
                    }
                    
                    // const excludeCloseTabEvents = chatHistory.filter(chat => chat.answerType !== "Close_Tab")
                    const excludeCloseTabEvents = chatHistory.filter(chat => {
                        const isCloseTab = chat.answerType === "Close_Tab";
                        const hasNoQuestionOrAnswer = !chat.question && !chat.answer;
                        return !(isCloseTab && hasNoQuestionOrAnswer);
                    });                    

                    // Make a copy of the array to avoid modifying the original
                    const result = [...excludeCloseTabEvents];
                    
                    // Process all elements except the last one
                    for (let i = 0; i < result.length - 1; i++) {
                        // Remove elements without answers (except the last one)
                        if (!result[i].hasOwnProperty('answer')) {
                        result[i] = null;
                        }
                    }
                    console.log("processRefreshedChatHistory before return", result)
                    
                    // Filter out null elements
                    return result.filter(item => item !== null);
                }

                const refreshedChat = processRefreshedChatHistory(window?.questionInfo?.chats);

                console.log('processRefreshedChatHistory final refresh chat', refreshedChat)

                // TODO: fix for open chatbot after refresh
                // const refreshedChat = window?.questionInfo?.chats;
                localStorage.setItem('chatData', JSON.stringify(refreshedChat));

                const chatHistory = window.shadow.querySelector('.cbw__chat');
                let receiverMainContainer = document.createElement('div');

                receiverMainContainer.className = 'cbw__chat_history';
                receiverMainContainer.id = 'chat-container_history';

                // (window?.questionInfo?.chats).forEach((item) => {    
                (refreshedChat).forEach((item) => {    
                    
                    let receiverHtml = '';
                    let userChatHistory = '';
                    const chatHistory = window.shadow.querySelector('.cbw__chat');
                    
                    // ai response
                    if(!!item.question) {
                        receiverHtml = botTextMessages(item);
                    }

                    if(!!item.answer) {
                      if(item.answerType == "file"){
                       userChatHistory = prepareFileUploadMessage({
                        fileName: item.fileName,
                        uploadStatus: "LOAD_FROM_HISTORY",
                        fileUrl: item.fileUpload
                       })
                    console.log('IN CHAT_HIST !!item', item, userChatHistory)

                      } else {
                        // userChatHistory = userTextMessages(item);
                        userChatHistory = userTextMessagesAI(item); // fix: same spacing after refresh
                        console.log({ userChatHistory })
                        }
                    }

                    receiverMainContainer.innerHTML += receiverHtml
                    receiverMainContainer.innerHTML += userChatHistory;

                    setTimeout(scrollToBottom, 100);

                    chatHistory.append(receiverMainContainer);

                    //show only if chat is ongoing
                    if(!message.isChatEnded){
                        const inputBox = window.shadow.querySelector(".cbw__footer");
                        inputBox.classList.remove('hide');
                        inputBox.classList.add('show');
                    }   
            });             
            } else if(message?.responseType === 'error') {
                window.responseError = true;

                const footerErrorBlock = window.shadow.getElementById('cbw__error');
                footerErrorBlock.classList.remove('hide');
                footerErrorBlock.classList.add('show');                  
                
                var chat = window.shadow.querySelector('.cbw__chat');
                // chat.innerHTML = '';
                // var questionContainer = document.createElement('div');
                // questionContainer.className = '';
                // questionContainer.style.color = '#FF1733';
                // questionContainer.style.backgroundColor = '#FF173333';
                // questionContainer.style.textAlign = 'center';
                // questionContainer.style.width = '100%';
                // questionContainer.style.fontSize = '13px';
                // questionContainer.style.padding = '5px 18px';
                // questionContainer.id = 'error';


                // questionContainer.innerHTML += \`<div class="">
                //     <p class="">
                //     \${window.questionInfo?.question}
                //     </p>
                // </div>\`;

                if(window.templateFormat === "static") {
                    footerErrorBlock.textContent += \`
                            \${window.questionInfo?.question}
                    \`;
                } 
                
                if(window.templateFormat === "dynamic") {
                    footerErrorBlock.textContent += \`
                            \${message?.message}
                    \`;
                }

                // chat.append(questionContainer);
                setTimeout(scrollToBottom, 100);

                const footerDiv = window.shadow.querySelector(".cbw__footer");
                
                if(footerDiv){
                    footerDiv.classList.remove('hide');
                    footerDiv.classList.add('show');

                    // disable input while loading AI response
                    const inputBox = window.shadow.getElementById('messageInput');
                    inputBox.style.cursor =  'not-allowed';
                    inputBox.disabled = true;

                    // disable file upload while loading AI response

                    const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
                    fileUploadBtn.style.cursor =  'not-allowed';
                    fileUploadBtn.disabled = true;   
                }
               
            }
        };

        window.ws.addEventListener('close', (event) => {
            console.log('Connection closed:', event.code, event.reason);
        });

        window.ws.onclose = () => {

            console.log('ON CLOSE', {isTimeOver: window.isTimeOver})
            if(window.isTimeOver) {
                displayErrorMessage();
            } 

        
            
            setTimeout(scrollToBottom, 100);
            var inputBox = window.shadow.querySelector(".cbw__footer");
            //NOTE: fixed remove input on refresh
            inputBox.classList.remove('show');
            // inputBox.classList.add('hide');
        };

        window.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        }
    };

    function storeData(message) {
        let storedArray = localStorage.getItem('chatData');

        if (storedArray === null) {
            // NOTE: fixed chat removed on refresh 
            console.log("storeData if");
            let array = [message];
            localStorage.setItem('chatData', JSON.stringify(array));

            return true;

        } else {
            console.log("storeData else");
            let storeValues = JSON.parse(storedArray);
            let indexOfQues = storeValues.findIndex((item) => message.question_id == item.question_id);

            if(indexOfQues == -1) {
                storeValues.push(message);
            } else {
                storeValues.splice(indexOfQues, 1);

                console.log("storeValues ============ ", storeValues);

                storeValues.push(message);

                localStorage.setItem('chatData', JSON.stringify(storeValues));
                return false;
            }

            // REMOVE THE LEAD QUESTION AFTER SUBMIT THE LEAD FORM
            let leadFilteredData = storeValues.filter(item => item.answerType !== 'Lead_Collection_Form');
            storeValues = leadFilteredData;
            
            localStorage.setItem('chatData', JSON.stringify(storeValues));

            return true;
        }
    }

    function ellipsizeFilename(filename) {
        const FILE_CHAR_LENGTH_FOR_ELLIPSE = 22
        if (filename.length <= FILE_CHAR_LENGTH_FOR_ELLIPSE) {
            return filename;
        }
        
        // Split the filename to preserve the extension
        const lastDotIndex = filename.lastIndexOf('.');
        let name, extension;
        
        if (lastDotIndex === -1) {
            name = filename;
            extension = '';
        } else {
            name = filename.substring(0, lastDotIndex);
            extension = filename.substring(lastDotIndex);
        }
        
        // Calculate how many characters to keep on each side
        const charsToKeep = Math.floor((18 - 3) / 2); // 21 - 3(for '...') = 18, then divide by 2
        const start = name.substring(0, charsToKeep);
        const end = name.substring(name.length - charsToKeep);
        
        return start + '...' + end + extension;
    }       


     const brandingCall = () => {
        fetch('${window.apiPath}chatbot/${window.template_code}', {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
            const dataVS =  window.chatbotConfiguration = data?.data?.chatbotConfiguration;
            // document.getElementsByClassName('cbw__assistant-name')[0].textContent = (data?.data?.templateDetails?.chatbotName != null && data?.data?.templateDetails?.chatbotName != undefined && data?.data?.templateDetails?.chatbotName != '') ? data?.data?.templateDetails?.chatbotName : "AI Assistant" || "AI_Chatbot";
            const shadowDiv = document.getElementById('cbw__shadow').shadowRoot;
            window.shadow.querySelectorAll('.cbw__assistant-name')[0].textContent = data?.data?.templateDetails?.chatbotName || "AI Assistant";
            socketCall('initial', dataVS);
        });
    };
    brandingCall();
    
    document.addEventListener('reactData', (event) => {
        const message = {
            template_code:  event.template_code,
        };
        window.ws.send(JSON.stringify(message));
      });`;
window.shadow.appendChild(socketScript);

const messageSendScript = document.createElement("script");
messageSendScript.innerHTML += `
        function loaderDisplay() {
            const timeOut =  window.questionCount  === 0 ? 1000 : 0;
            var chat = window.shadow.querySelector('.cbw__chat');
            var loaderContainer = document.createElement('div');
            loaderContainer.className = 'cbw__receiver-msg-box';
            loaderContainer.id = 'main-loader-' + window.loaderCount ;
            loaderContainer.innerHTML = \`
                <p class="cbw__receiver-msg">
                    <span class="loader"></span>
                </p>
            \`;
            chat.append(loaderContainer);

            // disable input while loading AI response
            const inputBox = window.shadow.getElementById('messageInput');
            inputBox.style.cursor =  'progress';
            inputBox.disabled = true;

            // disable file upload while loading AI response

            const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
            fileUploadBtn.style.cursor =  'not-allowed';
            fileUploadBtn.disabled = true;              

            setTimeout(scrollToBottom, 100); // Add delay to ensure scrolling works
        }

 function leadcollectionbody(leadData, title) {
    console.log("leadData", leadData);

    // Start building the HTML
    let optionsHTML = \`
        <div class="lead-form-section">
        <form id='contactForm'>
            <div class="form-group">
                <p class="form-title">\${leadData?.[0]?.formTitle}</p>    
    \`;

    // Loop through leadData and generate HTML based on answerType
    leadData?.forEach((dataItem) => {
        console.log("dataItem", dataItem);
        // Check if answerType is 'Input_box'
        if (dataItem.answerType === "Input_box") {
            optionsHTML += \`
                <label class="input-lable"></label>
                <input type="text" id="\${dataItem.question_id}" class="leadInputType lead-input"  placeholder="\${dataItem.question}">
            \`;
        }
        
        // Check if answerType is 'selectable_option'
       if (dataItem.answerType === "Selectable_Option") {
       optionsHTML += \`
        <div class="cbw__receiver-msg lead-radio">
            <div class="cbw__option-list-box custom-scrollbar">
                <label>\${dataItem.question}</label>

       \`;

    // Loop through the answers array
    dataItem.answers.forEach((answer,index) => {
    console.log("answer",answer)
  let manageIdx = 0;
    answer?.paramValue?.forEach((param, optionIndex) => {
        optionsHTML += \`
            <div class="cbw__option-list-radio">
                <input 
                    type="radio" 
                    class="leadRadioType" 
                    id="selectable_Option-\${param.value}-\${optionIndex}" 
                    data-id="\${dataItem.question_id}"
                    name="\${answer.id}"
                    value="\${param.value}" 
                    hidden
                >
                <label 
                    class="radio-label" 
                    for="selectable_Option-\${param.value}-\${optionIndex}">
                    \${param.value}
                </label>
            </div>
        \`;
    manageIdx++;
    });
    });

    // Close the HTML structure
    optionsHTML += \`
            </div>
        </div>
    \`;
}

 if (dataItem.answerType === "Searchable_Dropdown") {
 
    dataItem?.answers?.forEach((answer, index) => {
        let paramValue = "";
       optionsHTML += \` <label class="input-lable">\${dataItem.question}</label>
        <select id="serviceSelect_\${index}" data-id="\${dataItem.question_id}" class=" lead-select"> \`;
      answer?.paramValue?.forEach((param, id) => {
        optionsHTML += \`
                

           
                \${param.value ? \`<option value="\${param.value}" class="dropdown-option-btn">\${param.value}</option>\` : ""}
        \`;
})

        optionsHTML += \`
            </select>
        \`;
        
    });
}

    });
    

    
    // Finish building the form with the submit button
    optionsHTML += \`
            <div class="form-button select-btn">
            <p id="errorMessage" class="errorMessageShow"></p>
            <button type="button" class="select-btn"  id='form-lead-collection'>Start Chat</button>
            </div>
        </form>
        </div>
    \`;

    return optionsHTML;
}


    function setIntervalFunc() {
            
        if (window.intervalId) {
            clearInterval(window.intervalId);
            clearInterval(window.timeCounter);
            window.intervalId = null;
        }

        window.intervalId = setInterval(() => {
            
                window.timeCounter = parseInt(localStorage.getItem('timeCounter'), 10) || 0;
                // window.timeCounter++;

                // CHECK EPOCH TIME
                const getLocalStorageEpochTime = localStorage.getItem('epchTime') || 0;
                const currentEpochTime =  Date.now();
                console.log('currentEpochTime', currentEpochTime);
                var difference = currentEpochTime - getLocalStorageEpochTime;
                const diffMs = Math.abs(difference); // Absolute value to avoid negative differences
                var minuteDifference = diffMs/(1000 * 60);

                const questionId = window.questionInfo?.question_id;
                // localStorage.setItem("timeCounter", window.timeCounter);
                // const timeCounter = localStorage.getItem('timeCounter');
                // console.log("timeCounter", timeCounter);
                console.log({ minuteDifference })
                if (parseInt(minuteDifference) >= window.SESSION_TIMEOUT_MINUTES) {
                    console.log('isTimeOver in setInterval', {isTimeOver: window.isTimeOver})
                    window.isTimeOver = true;
                    localStorage.removeItem("chatData");

                    clearInterval(window.intervalId); // Stop the interval once the condition is met

                    const message = {
                        sender: 'you',
                        question: window.questionInfo?.question,
                        question_id: window.questionInfo?.question_id,
                        questionId: window.questionInfo?.questionId,
                        roomKey: window.roomKey,
                        timeout: Date.now(),
                        answerType: 'Close_Tab',
                        ideal: true
                    };

                    window.shadow.getElementById(questionId)?.classList?.add?.('pointer-event');
                    
                    console.log("window.templateFormat :::: ", window.templateFormat)

                    // SHOW / HIDE THE INPUTBOX FOR FULLY AI
                    if (window.templateFormat === "dynamic") {
                        const inputBoxAi = window.shadow.querySelector(".cbw__footer");
                        inputBoxAi.classList.add('hide');
                        inputBoxAi.classList.remove('show');
                    }
                        
                    // SHOW / HIDE THE INPUTBOX FOR STATIC
                    if (window.templateFormat === "static") {
                        window.shadow.getElementById(questionId)?.classList?.add?.('pointer-event');
                        const inputBox = window.shadow.querySelector(".cbw__footer");
                        if (window.questionInfo?.answerType === 'Input_box') {
                            if (inputBox) {
                                inputBox.classList.add('hide');
                                inputBox.classList.remove('show');
                            }
                        }
                    }

 
                    
                    console.log('ready state', window.ws.readyState, WebSocket.OPEN)
                    // if (window.ws && window.ws.readyState === WebSocket.OPEN) {
                        window.ws.send(JSON.stringify(message));

                        // fix: explicitely close the socket and display error
                        displayErrorMessage();
                        ws.close()                       
                    // }

                    // window.timeCounter = 0;
                    // broadcastMessage(0, "timeCounter");    
                    // localStorage.setItem('timeCounter', 0);

                    // to test comment it
                    setCurrentEpochTime();

                    // IS TIME OVER THEN DISPLAY ERROR MESSAGE
                    broadcastMessage("SHOW_ERROR_MSG", "timeCounter");

                    // broadcastMessage("CloseAllTabs");

                    // if (window.ws && window.ws.readyState === WebSocket.OPEN) {
                    //     window.ws.send(JSON.stringify(message));
                    // }
                    
                    return;
                }
        }, 1000);
    }

    function setCurrentEpochTime() {
        const currentEpochTime =  Date.now();
        localStorage.setItem('epchTime', currentEpochTime);
    }

    const uploadAttachmentBtn = window.shadow.querySelector(".cbw__attachement-btn");

    uploadAttachmentBtn.addEventListener("click", function (event) {
    event.preventDefault();
    window.shadow.getElementById("input__attachment").click();
    });

    //toggle footer accordion
    const accordion = window.shadow.querySelector('.cbw__accordion');
    const accordionContent = window.shadow.querySelector('.cbw__accordion-content');
    const accordionArrow = window.shadow.querySelector('.cbw__accordion-arrow');

    if (accordion && accordionContent && accordionArrow) {
        accordion.addEventListener('click', function() {
            accordionContent.classList.toggle('open');
            accordionArrow.classList.toggle('open');
        });
    }    

    window.shadow.getElementById("input__attachment").addEventListener("change", onChangeFileUpload);
    
    
    var botSendBtn = window.shadow.querySelector(".cbw__send-btn")
    var messageInput = window.shadow.getElementById("messageInput");
    messageInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            event.preventDefault(); // Prevent the default action (adding a new line)

            // if input empty / whitespace
            if(messageInput.value.trim() === "") return;

            submitInputData();
        }
    });

    // Function to detect if page is being reloaded
    // const isPageReload = () => {
    //     return (
    //         (window.performance.navigation && window.performance.navigation.type === 1) ||
    //         (window.performance.getEntriesByType('navigation')[0]?.type === 'reload')
    //     );
    // };    

    // ON REFRESH SEND EVENT
    function handleBeforeUnload(event) {
        // if(!isPageReload()) return;

         const message = {
            sender: 'you',
            question: window.questionInfo?.question,
            question_id: window.questionInfo?.question_id,
            questionId: window.questionInfo?.questionId,
            answer: messageInput.value,
            timeout: Date.now(),
            answerType: 'Close_Tab',
            referenceName:  window.questionInfo?.referenceName,
            templateId: window?.questionInfo?.templateId,
            tenantId: window?.questionInfo?.tenantId,
            userUUID: window.questionInfo?.userUUID,
            ideal: false,
        };

        // console.log(message);
        window.ws.send(JSON.stringify(message));

        return null;

        event.preventDefault();
        event.returnValue = "";
    }

    // NOTE: now will handle from node cron
    // window.addEventListener("beforeunload", handleBeforeUnload);

    window.addEventListener("unload", () => {

        // if(!isPageReload()) return;
                
        // const message = {
        //     sender: 'you',
        //     question: window.questionInfo?.question,
        //     question_id: window.questionInfo?.question_id,
        //     questionId: window.questionInfo?.questionId,
        //     roomKey: window.roomKey,
        //     timeout: Date.now(),
        //     answerType: 'Close_Tab',
        //     referenceName: window.questionInfo?.referenceName,
        //     templateId: window?.questionInfo?.templateId,
        //     tenantId: window?.questionInfo?.tenantId,
        //     userUUID: window.questionInfo?.userUUID,
        //     ideal: false,
        // };

        localStorage.removeItem("isFirstLoaded");
        localStorage.removeItem("chatData");

        // Send the message only when the tab is actually closing
        // window.ws.send(JSON.stringify(message));
        

        // ON CLOSE TAB CLOSED ALL CONNECTION
        broadcastMessage("CloseAllTabs");

        return null;
    });

    messageInput.addEventListener('input', () => {
        clearInterval(window.intervalId);
        
        // window.timeCounter = 0;
        // broadcastMessage(0, "timeCounter");
        // localStorage.setItem("timeCounter", 0);

        // FIX: auto height increase as soon as user starts typing
        // messageInput.style.height = 'auto';
        if(messageInput.value === '') {
            messageInput.style.height = '26px';
        }
        messageInput.style.height = Math.min(messageInput.scrollHeight, 150) + 'px';
        var cbwError = window.shadow.getElementById('cbw__error');
        var sendBtn = window.shadow.querySelector('.cbw__send-btn');
        cbwError.classList.remove('show');
        cbwError.classList.add('hide');
        cbwError.textContent = '';
        sendBtn.classList.remove('transform-div');
    });

    // IF RESET IN CURRENT TAB THEN CONNECTION WILL BE CLOSED
    window.addEventListener('storage', (event) => {
        // console.log("=========", event.key);
        if (event.key === 'isReset') {
            // console.log('Close signal received via localStorage.');
            // if (ws.readyState === WebSocket.OPEN) {
            //     window.ws.close();
            // }

        }

        // CHATBOT UI SHOW / HIDE
        if (event.key === "chatbotOpen") {
            const chatbotStartBtn = window.shadow.querySelector(".cbw__bot-start-btn");
            const getChatbotOpened = localStorage.getItem('chatbotOpen');
            console.log(getChatbotOpened, 'getChatbotOpened')
            var cbwBody = window.shadow.querySelector(".cbw__body");
            if (getChatbotOpened === 'true') {
                cbwBody.classList.add('show');
                cbwBody.classList.remove('hide');
                chatbotStartBtn.classList.add('hide');
                chatbotStartBtn.classList.remove('show');
            } else {
                console.log('in');
                cbwBody.classList.add('hide');
                cbwBody.classList.remove('show');
                chatbotStartBtn.classList.add('show');
                chatbotStartBtn.classList.remove('hide');
            }
        }

        
    });


    // RESET THE CHAT
    const resetChat = window.shadow.querySelector("#btn-reset");
    resetChat.addEventListener('click', (event) => {
        event.preventDefault();
        // window.timeCounter = 0;
        
        window.isTimeOver = false;

        if (window.templateFormat === 'static') {
            window.staticReady = false;
            window.pendingStartChat = false;
        }

        localStorage.removeItem("roomKey");
        localStorage.setItem("isReset", true);
        sessionStorage.removeItem("roomKey");
        localStorage.removeItem("chatData");
        localStorage.removeItem("isFirstLoaded");

        const footerErrorBlock = window.shadow.getElementById('cbw__error');

        if(footerErrorBlock){
          footerErrorBlock.classList.remove('show');
          footerErrorBlock.classList.add('hide');            
        }        
        
        window.roomKey = "";

        const message = {
            sender: 'you',
            question: window.questionInfo?.question || "",
            question_id: window.questionInfo?.question_id,
            questionId: window.questionInfo?.questionId,
            roomKey: window.roomKey,
            answer: "",
            timeout: Date.now(),
            answerType: 'Close_Tab',
            referenceName:  window.questionInfo?.referenceName,
            templateId: window?.questionInfo?.templateId,
            tenantId: window?.questionInfo?.tenantId,
            userUUID: window.questionInfo?.userUUID,
            ideal: false,
        };
        window.ws.send(JSON.stringify(message));

        console.log(" ::::  - DATA SEND");

        window.questionList = [];
        // window.ws.c(1000, 'Closing the connection normally');

        broadcastMessage("CloseAllTabs");

        broadcastMessage("oninit", "oninit");

        console.log(" ::::  - code init");

        setCurrentEpochTime();

        // remove calendly if exist
        const calenderId = window.questionInfo.question_id || 'calendar1'; // static id / calendar

        const calendlyWindow = window.shadow.getElementById(calenderId);
        if(calendlyWindow){
            calendlyWindow.remove();

            // switch back container visiblity from block to none, div stays in dom
            const calendlyContainer = window.shadow.querySelector(".cbw__chat__calendar")
            calendlyContainer.style.display = "none";

            // bring back cbw chat div visibility
            const chatContainer = window.shadow.querySelector(".cbw__chat");

            if(chatContainer){
                chatContainer.style.display = "flex"
            }
        }     

        let resetChat = window.shadow.querySelector('.cbw__chat');

        if(resetChat){
            resetChat.style.display = 'flex';
            resetChat.innerHTML = '';
        }
            
        var loaderContainer = document.createElement('div');
        loaderContainer.className = 'cbw__receiver-msg-box';
        loaderContainer.id = 'first-loader';
        loaderContainer.innerHTML = \`
                                <p class="cbw__receiver-msg">
                                    <span class="loader"></span>
                                </p>
                            \`;
        resetChat.append(loaderContainer);

        setTimeout(() => {
            const getRoomKey = localStorage.getItem("roomKey");
            window.roomKey = getRoomKey;

            console.log("isConnectionExists  ::: room key", getRoomKey)

            // REINIT THE SOCKET START
            socketCall('', window.chatbotConfiguration, getRoomKey);
            // REINIT THE SOCKET END
        }, 300);

    }); // , {once : true}


    function displayErrorMessage() {
        // let isVisible = window.shadow.querySelector("#chat-container");
        // (isVisible.children[0]).style.display = 'block';
        // console.log("=============", isVisible);

        // remove calendly if exist
        const calenderId = window.questionInfo.question_id || 'calendar1'; // static id / calendar

        const calendlyWindow = window.shadow.getElementById(calenderId);
        if(calendlyWindow){
            calendlyWindow.remove();

            // switch back container visiblity from block to none, div stays in dom
            const calendlyContainer = window.shadow.querySelector(".cbw__chat__calendar")
            calendlyContainer.style.display = "none";

            // bring back cbw chat div visibility
            const chatContainer = window.shadow.querySelector(".cbw__chat");

            if(chatContainer){
                chatContainer.style.display = "flex"
            }
        }          

        var chat = window.shadow.querySelector('.cbw__chat');
        chat.innerHTML = '';
        var questionContainer = document.createElement('div');
        questionContainer.className = 'isTimeOver'; // displayNone
        questionContainer.style.color = 'grey';
        questionContainer.style.textAlign = 'center';
        questionContainer.style.width = '100%';
        questionContainer.style.fontSize = '13px';
        questionContainer.id = 'error';
        questionContainer.innerHTML += \`<div class="">
            <p class="">
                Your chat session has ended. To start a new chat,<br/> please <a href="javascript:void(0);" class="cbw__restart_btn"> click here.</a>
            </p>
        </div>\`
        chat.append(questionContainer);

        var restartBtn = window.shadow.querySelector('.cbw__restart_btn');
        if(restartBtn) {
            restartBtn.addEventListener("click", () => {

                // window.questionList = [];
                // socketCall('', window.chatbotConfiguration, window.roomKey);
                // window.timeCounter = 0;
                
                window.isTimeOver = false;
                setCurrentEpochTime();

                localStorage.removeItem("roomKey");
                localStorage.setItem("isReset", true);
                sessionStorage.removeItem("roomKey");
                localStorage.removeItem("chatData");
                localStorage.removeItem("isFirstLoaded");

                window.roomKey = "";

                const message = {
                    sender: 'you',
                    question: window.questionInfo?.question,
                    question_id: window.questionInfo?.question_id,
                    questionId: window.questionInfo?.questionId,
                    roomKey: window.roomKey,
                    // answer: "",
                    timeout: Date.now(),
                    answerType: 'Close_Tab',
                    referenceName:  window.questionInfo?.referenceName,
                    templateId: window?.questionInfo?.templateId,
                    tenantId: window?.questionInfo?.tenantId,
                    userUUID: window.questionInfo?.userUUID,
                    ideal: false,
                };
                window.ws.send(JSON.stringify(message));
                window.questionList = [];
                // window.ws.c(1000, 'Closing the connection normally');

                broadcastMessage("CloseAllTabs");

                broadcastMessage("oninit", "oninit");

                let resetChat = window.shadow.querySelector('.cbw__chat');
                resetChat.innerHTML = '';
                var loaderContainer = document.createElement('div');
                loaderContainer.className = 'cbw__receiver-msg-box';
                loaderContainer.id = 'first-loader';
                loaderContainer.innerHTML = \`
                                        <p class="cbw__receiver-msg">
                                            <span class="loader"></span>
                                        </p>
                                    \`;
                resetChat.append(loaderContainer);

                setTimeout(() => {
                    const getRoomKey = localStorage.getItem("roomKey");
                    window.roomKey = getRoomKey;
        
                    console.log("isConnectionExists  ::: room key", getRoomKey)
        
                    // REINIT THE SOCKET START
                    socketCall('', window.chatbotConfiguration, getRoomKey);
                    // REINIT THE SOCKET END
                }, 100);
            }); // , {once : true}
        }
    }

    function broadcastMessage(message, types = 'broadcast') {

        if (navigator.serviceWorker.controller) {
            if(types === 'oninit') {
                const dynamiCode = generateUniqueCode();

                navigator.serviceWorker.controller.postMessage({
                    type: 'message',
                    payload: "oninit",
                    data: window.connectionLink,
                    code: dynamiCode
                });
            } else if(types === 'sendToAll') {
                navigator.serviceWorker.controller.postMessage({
                    type: 'sendToAll',
                    payload: message
                });
            } else if(types === 'timeCounter') {
                navigator.serviceWorker.controller.postMessage({
                    type: 'timeCounter',
                    payload: message
                });
            } else if(types === 'radioChangeEvent' || types === 'dropDownChangeEvent') {
                navigator.serviceWorker.controller.postMessage({
                    type: types,
                    payload: message
                });
            } else {
                navigator.serviceWorker.controller.postMessage({
                    type: 'broadcast',
                    payload: message,
                    data: window.connectionLink
                });
            }
        }
    }

    navigator.serviceWorker.addEventListener('message', (event) => {
        const { type, payload, code} = event.data;
        if (type === 'broadcast') {
            window.ws.close();
        }
        
        if (type === 'message') {
            if (document.visibilityState == 'hidden') {
                console.log("::: oninit")
                
                window.roomKey = code;
                console.log("::: room key hidden  ", window.roomKey)
                socketCall('', window.chatbotConfiguration, window.roomKey);
            } 
            // else {
            //     console.log("::: room key visible  ", window.roomKey)
            //     socketCall('', window.chatbotConfiguration, window.roomKey);
            // }
        }

        if (type === 'timeCounter') {
            window.timeCounter = payload;
            console.log("broadcast ::: ", payload);
            // localStorage.setItem("timeCounter", payload);

            // Remove footer from all other tabs
            const inputFooter = window.shadow.querySelector('.cbw__footer');
            
            if(inputFooter){
                inputFooter.classList.remove('show');
                inputFooter.classList.add('hide');
            }              

            if (payload == "SHOW_ERROR_MSG") {   
                displayErrorMessage();
            }               
        }
        
        if (type === 'radioChangeEvent') {
            console.log("::: change", type, payload)
            const radioData = window.shadow.getElementById(payload);
            radioData.checked = true;            
        }
        
        if(type === 'dropDownChangeEvent') {
            console.log("::: change", type, payload)
            let updatedValue = payload.split('-');
            
            const dropDownEle = window.shadow.getElementById("select-selected"+updatedValue[1]);
            // const parentDiv = dropDownEle.parentElement;
            // const selectElement = parentDiv.querySelector('select');

            console.log("::: change dropdown", dropDownEle);
            console.log("::: change updatedValue", updatedValue);
            console.log("::: change updatedValue[0] ", updatedValue[0]);

            dropDownEle.textContent = updatedValue[0];
        }

        if (type === 'sendToAll') {
            const tempChatData = JSON.parse(payload);
            
            console.log( " :::: sendToAll ", tempChatData);
            console.log( " :::: sendToAll document.visibilityState", document.visibilityState);

            if (tempChatData?.answer !== null && tempChatData?.answer !== undefined) {
             
              if(tempChatData?.answerType === "file"){
                let tempChat = window.shadow.querySelector('.cbw__chat');
                let tempContainer = document.createElement('div');

                    function ellipsizeFilename(filename) {
                        const FILE_CHAR_LENGTH_FOR_ELLIPSE = 22
                        if (filename.length <= FILE_CHAR_LENGTH_FOR_ELLIPSE) {
                            return filename;
                        }
                        
                        // Split the filename to preserve the extension
                        const lastDotIndex = filename.lastIndexOf('.');
                        let name, extension;
                        
                        if (lastDotIndex === -1) {
                            name = filename;
                            extension = '';
                        } else {
                            name = filename.substring(0, lastDotIndex);
                            extension = filename.substring(lastDotIndex);
                        }
                        
                        // Calculate how many characters to keep on each side
                        const charsToKeep = Math.floor((18 - 3) / 2); // 21 - 3(for '...') = 18, then divide by 2
                        const start = name.substring(0, charsToKeep);
                        const end = name.substring(name.length - charsToKeep);
                        
                        return start + '...' + end + extension;
                    }

                tempContainer.innerHTML += \`
                    <div class="cbw__sender-file-msg-box" style="cursor: pointer;" onclick="window.open('\${tempChatData.fileUpload}', '_blank')">
                        <div class="cbw__sender-file-msg">
                            \${ellipsizeFilename(tempChatData.fileName)}
                            <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-left: 10px">
                                <path d="M1 13C1 15.8284 1 17.2426 1.87868 18.1213C2.75736 19 4.17157 19 7 19H13C15.8284 19 17.2426 19 18.1213 18.1213C19 17.2426 19 15.8284 19 13" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                <path d="M10 1L10 14M10 14L6 9.625M10 14L14 9.625" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                    </div>
                \`

                tempChat.append(tempContainer);
              } else {
                let tempChat = window.shadow.querySelector('.cbw__chat');
                let tempContainer = document.createElement('div');
                tempContainer.className = 'cbw__sender-msg-box';
                tempContainer.innerHTML += \` <div class="cbw__sender-msg-box" id="">
                    <div class="cbw__sender-msg">
                        <p>
                        \${tempChatData?.answer}
                        </p>
                    </div>
                </div> \`;
                tempChat.append(tempContainer);
             }
          }
        }
    });
   
    function checkError() {
        var chat = window.shadow.querySelector('.cbw__chat');
        var messageInput = window.shadow.getElementById('messageInput');
        var messageD = messageInput.value;
        
        var reference = window?.questionInfo?.referenceName;
        const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
        const contactNumberRegex = /^\\d{7,15}$/;
        const firstNameRegex = /^[A-Za-z]{30}$/;
        var cbwError = window.shadow.getElementById('cbw__error');
        var sendBtn = window.shadow.querySelector('.cbw__send-btn');
        cbwError.classList.remove('show');
        cbwError.classList.add('hide');
        sendBtn.classList.remove('transform-div');

        cbwError.textContent = '';
        if (messageD) {
            if(messageD?.length > 500) {
                cbwError.classList.remove('hide');
                cbwError.classList.add('show');
                sendBtn.classList.add('transform-div');
                cbwError.textContent = 'Message too long! Please keep it under 500 characters.';
                return;
            }
            if(reference === 'email') {
                if(!emailRegex.test(messageD)) {
                    cbwError.classList.remove('hide');
                    sendBtn.classList.add('transform-div');

                    cbwError.classList.add('show');
                    cbwError.textContent = 'Please enter in a valid format.'
                    return;
                }
            } else  if(reference === 'phone'){
                if(!contactNumberRegex.test(messageD)) {
                    cbwError.classList.remove('hide');
                    cbwError.classList.add('show');
                    sendBtn.classList.add('transform-div');
                    cbwError.textContent = 'Please enter a valid phone number with a minimum of 7 digits and a maximum of 15 digits.'
                    return;
                }
            } else if(reference === 'first_name') {
                // if(!firstNameRegex.test(messageD)) {
                //     cbwError.classList.remove('hide');
                //     cbwError.classList.add('show');
                //     cbwError.textContent = 'Only maximum 30 characters allowed in first name.';
                //     return;
                // }
            } else if(reference === 'last_name') {
                // if(!firstNameRegex.test(messageD)) {
                //     cbwError.classList.remove('hide');
                //     cbwError.classList.add('show');
                //     cbwError.textContent = 'Only maximum 30 characters allowed in last name.';
                //     return;
                // }
            }
            cbwError.classList.add('hide');
            cbwError.classList.remove('show');
        }
    }

    async function onChangeFileUpload() {
    const MAX_DOCUMENT_SIZE = 15 * 1024 * 1024;
    const MAX_IMAGE_SIZE = 15 * 1024 * 1024;
    const MAX_VIDEO_SIZE = 50 * 1024 * 1024;

    const ALLOWED_DOCUMENT_TYPES = ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.xls', '.xlsx', '.ppt', '.pptx'];
    const ALLOWED_IMAGE_TYPES = ['.jpeg', '.jpg', '.png', '.tiff'];
    const ALLOWED_VIDEO_TYPES = ['.mp4', '.avi', '.mov'];
    const ALLOWED_AUDIO_TYPES = ['.mp3', '.wav'];

    var fileInput = window.shadow.getElementById("input__attachment");
    const footerErrorBlock = window.shadow.getElementById('cbw__error');

    if (!fileInput.files.length) {
        console.error("No file selected!");
        return;
    }

    const selectedFile = fileInput.files[0];
    console.log({ selectedFile });

    const { name: fileName, size } = selectedFile;
    console.log({ fileName, size });

    const fileExtension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();

    // Validate file type
    let isValidType = false;

    if (ALLOWED_DOCUMENT_TYPES.includes(fileExtension) ||
        ALLOWED_IMAGE_TYPES.includes(fileExtension) ||
        ALLOWED_VIDEO_TYPES.includes(fileExtension) ||
        ALLOWED_AUDIO_TYPES.includes(fileExtension)) {
        isValidType = true;
    }

    if (!isValidType) {
        footerErrorBlock.classList.remove('hide');
        footerErrorBlock.classList.add('show');
        footerErrorBlock.textContent = 'Unsupported file format. Please upload a valid file !'
        return;
    }

    // Validate file size
    const MAX_FILE_SIZE_LIMIT = 15 * 1024 * 1024; // Using the original limit for now

    if(ALLOWED_VIDEO_TYPES.includes(fileExtension)){
        if (size > MAX_VIDEO_SIZE) {
            footerErrorBlock.classList.remove('hide');
            footerErrorBlock.classList.add('show');
            footerErrorBlock.textContent = 'File size exceeds the limit. Please upload a video under 50 MB';
            return;
        }
    } else if (size > MAX_FILE_SIZE_LIMIT) {
        footerErrorBlock.classList.remove('hide');
        footerErrorBlock.classList.add('show');
        footerErrorBlock.textContent = 'File size exceeds the limit. Please upload a file under 15 MB';
        return;
    } else {
        // If the file is valid, remove the error message
        footerErrorBlock.classList.remove('show');
        footerErrorBlock.classList.add('hide');
        footerErrorBlock.textContent = ''; // Clear the error text as well
    }

    const formData = new FormData();
    formData.append('file', selectedFile);

    prepareFileUploadMessage({
        fileName: fileName,
        uploadStatus: 'UPLOADING'
    });

    setTimeout(scrollToBottom, 100);

    try {
        const tenantId = localStorage.getItem('tenantId')
        const templateId = localStorage.getItem('templateId');

        const response = await fetch(window.apiPath + 'template/upload/' + tenantId + '/' + templateId, {
            method: 'POST',
            body: formData,
            headers: {
                "Authorization": 'Bearer ' + window.template_code
            }
        });

        if (!response.ok) {
        }

        const data = await response.json();

        prepareFileUploadMessage({
            fileName: fileName,
            uploadStatus: 'UPLOADED',
            fileUrl: data?.data?.signedUrl
        });

        let fileUploadJson;
        let localStorageMsg;

        if(window.questionInfo.responseType === "chat_history"){
            const loadedChatHistory = window.questionInfo.chats
            const lastQuestion = loadedChatHistory[loadedChatHistory.length - 1].question || window.questionInfo?.message       
            
            fileUploadJson = {
                question: lastQuestion,
                answer: "The user has uploaded a file to the platform",
                answerType: 'file',
                fileName: fileName,
                fileUpload: data.data.signedUrl
            }

            localStorageMsg = {
                sender: 'you',
                question: lastQuestion,
                answer: "The user has uploaded a file to the platform",
                answerType: 'file',
                fileName: fileName,
                fileUpload: data.data.signedUrl                 
            }            
        } else if(window.templateFormat === "dynamic"){
            fileUploadJson = {
                sender: 'you',
                question: window.questionInfo?.message,
                answer: "The user has uploaded a file to the platform",
                answerType: 'file',
                fileName: fileName,
                fileUpload: data.data.signedUrl
            }

            localStorageMsg = {
                sender: 'you',
                question: window.questionInfo?.message,
                answer: "The user has uploaded a file to the platform",
                answerType: 'file',
                fileName: fileName,
                fileUpload: data.data.signedUrl                 
            }
        } else {
           fileUploadJson = {
            ...window.questionInfo,
            sender: 'you',
            answer: data.data.signedUrl,
            fileName                
           }

           localStorageMsg = {
                ...window.questionInfo,
                answer: data.data.signedUrl,
                answerType: 'file',
                fileName                    
           }
        }

        // const fileUploadJson = {
        //     question: window.questionInfo?.message,
        //     answer: "The user has uploaded a file to the platform",
        //     answerType: 'file',
        //     fileName: fileName,
        //     fileUpload: data.data.signedUrl
        // };

        window.ws.send(JSON.stringify(fileUploadJson));
        // window.ws.send(JSON.stringify(fileUploadJson));

        //  fix: this leads to double file while chatting across the tab
        // if(window.templateFormat === "dynamic"){
        //     broadcastMessage(JSON.stringify(fileUploadJson), "sendToAll");
        // }
        // for static socket sends event for all other tabs

        // appendMessageToLocalStorage({
        //     sender: 'you',
        //     question: window.questionInfo?.message,
        //     answer: "The user has uploaded a file to the platform",
        //     answerType: 'file',
        //     fileName: fileName,
        //     fileUpload: data.data.signedUrl        
        // })

        appendMessageToLocalStorage(localStorageMsg)

        setTimeout(scrollToBottom, 100);
        window.loaderCount = window.loaderCount + 1;
        loaderDisplay();
        // window.ws.send(JSON.stringify({
        //     question: window.questionInfo?.message,
        //     answer: "The user has uploaded a file to the platform",
        //     answerType: 'file',
        //     fileName: fileName,
        //     fileUpload: data.data.signedUrl
        // }));

        // appendMessageToLocalStorage({
        //     sender: 'you',
        //     question: window.questionInfo?.message,
        //     answer: "The user has uploaded a file to the platform",
        //     answerType: 'file',
        //     fileName: fileName,
        //     fileUpload: data.data.signedUrl        
        // })

        // setTimeout(scrollToBottom, 100);
        // window.loaderCount = window.loaderCount + 1;
        // loaderDisplay();
    } catch (error) {
        footerErrorBlock.classList.remove('hide');
        footerErrorBlock.classList.add('show');
        footerErrorBlock.textContent = 'File upload incomplete. Please try again !';
        console.error("Upload failed:", error);


        // enable file upload button once file uploaded

        const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
        fileUploadBtn.style.cursor =  'pointer';
        fileUploadBtn.disabled = false;  

        // enable input once file uploaded

        const inputBox = window.shadow.getElementById('messageInput');
        inputBox.style.cursor =  'text';
        inputBox.disabled = false;          
    } finally {
        // Reset file input
        fileInput.value = "";
    }
} 


    function submitInputData() {

        var chat = window.shadow.querySelector('.cbw__chat');
        var messageInput = window.shadow.getElementById('messageInput');
        var messageD = messageInput.value;
        var cbwError = window.shadow.getElementById('cbw__error');
        var sendBtn = window.shadow.querySelector('.cbw__send-btn');
        var reference = window?.questionInfo?.referenceName;
        const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
        const contactNumberRegex = /^\\d{7,15}$/;
        const firstNameRegex = /^[A-Za-z]{30}$/;
        cbwError.classList.remove('show');
        cbwError.classList.add('hide');
        cbwError.textContent = '';
        sendBtn.classList.remove('transform-div');
        cbwError.textContent = '';
        if (messageD) {
                if(messageD?.length > 500) {
                    cbwError.classList.remove('hide');
                    cbwError.classList.add('show');
                    // sendBtn.classList.add('transform-div');
                    cbwError.textContent = 'Message too long! Please keep it under 500 characters.';
                    return;
                }
                if(reference === 'email') {
                    if(!emailRegex.test(messageD)) {
                        cbwError.classList.remove('hide');
                        // sendBtn.classList.add('transform-div');

                        cbwError.classList.add('show');
                        cbwError.textContent = 'Please enter in a valid format.'
                        return;
                    }
                } else  if(reference === 'phone'){
                    if(!contactNumberRegex.test(messageD)) {
                        cbwError.classList.remove('hide');
                        cbwError.classList.add('show');
                        // sendBtn.classList.add('transform-div');
                        cbwError.textContent = 'Please enter a valid phone number with a minimum of 7 digits and a maximum of 15 digits.'
                        return;
                    }
                } else if(reference === 'first_name') {
                    // if(!firstNameRegex.test(messageD)) {
                    //     cbwError.classList.remove('hide');
                    //     cbwError.classList.add('show');
                    //     cbwError.textContent = 'Only maximum 30 characters allowed in first name.';
                    //     return;
                    // }
                } else if(reference === 'last_name') {
                    // if(!firstNameRegex.test(messageD)) {
                    //     cbwError.classList.remove('hide');
                    //     cbwError.classList.add('show');
                    //     cbwError.textContent = 'Only maximum 30 characters allowed in last name.';
                    //     return;
                    // }
                }
                cbwError.classList.add('hide');
                cbwError.classList.remove('show');
                
                //  STATIC CONDITON COMMENT

                if(window.templateFormat === "static") {
                    const message = {
                        sender: 'you',
                        question: window.questionInfo?.question,
                        question_id: window.questionInfo?.question_id,
                        questionId: window.questionInfo?.questionId,
                        roomKey: window.roomKey,
                        answer: messageInput.value,
                        timeout: Date.now(),
                        answerType: window.questionInfo?.answerType,
                        referenceName:  window.questionInfo?.referenceName,
                        templateId: window?.questionInfo?.templateId,
                        tenantId: window?.questionInfo?.tenantId,
                        userUUID: window.questionInfo?.userUUID,
                        ideal: false,
                    };
                    prepareSenderData(message);
                }
                if(window.templateFormat === "dynamic") {
                // TEST: after refresh chat_history event the message lead to invalid respo
                if(window.questionInfo.responseType == "chat_history"){
                const loadedChatHistory = window.questionInfo.chats
                 var lastQuestionX = loadedChatHistory[loadedChatHistory.length - 1].question || ""
                }

                    const dynamicMessage = {
                        sender: 'you',
                        question: lastQuestionX || window.questionInfo.message,
                        // question: window.questionInfo.message,
                        roomKey: window.roomKey,
                        answer: messageInput.value,
                        chaType: "ai",
                        // timeout: Date.now(),
                        // ideal: false,
                    };
                    prepareSenderData(dynamicMessage);
                }

                // to trace session
                setCurrentEpochTime()
                setIntervalFunc();

                messageInput.style.height = '26px';
                messageInput.value = '';
        }
    }
    if(botSendBtn) {
        botSendBtn.addEventListener("click", (event) => {
            event.preventDefault(); // Prevent default action

            // if input empty / whitespace
            if(messageInput.value.trim() === "") return;

            submitInputData();
            
        });
    }
    async function fetchAIanswerData(msg) {
        loaderDisplay();

        // Await the fetch call and handle the response
        const response = await fetch('https://chatapi.answeringlegal.com/openAI/',
        {
            method: 'POST', // Specify the HTTP method as POST
            headers: {
                'Content-Type': 'application/json' // Set the Content-Type to JSON
            },
            body: JSON.stringify({
                "prompt": msg,
            }) // Convert the JavaScript object to a JSON string
        });
    
        // Check if the response is ok (status in the range 200-299)
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

    
        // Parse and return the JSON response
        const data = await response.json();
        return data;
    }

    // function appendMessageToLocalStorage(msg){
    //   const chatData = localStorage.getItem('chatData') || '[]';
    //   const parsedData = JSON.parse(chatData)

    //   const isExistInChat = parsedData.some(item => item.answer === msg.answer && item.question === msg.question);

    //   if(isExistInChat) return;

    //   parsedData.push(msg);
    //   localStorage.setItem('chatData', JSON.stringify(parsedData));
    // }

    function appendMessageToLocalStorage(msg) {
  console.log("APPENDED TO LOCAL STORAGE", msg);
  const chatData = localStorage.getItem('chatData') || '[]';
  const parsedData = JSON.parse(chatData);

  const isAIResponse = msg.sender !== "you" && !!msg?.message;

  if (isAIResponse) {
    parsedData.push({
      question: msg?.message,
      roomKey: window.roomKey,
      chaType: "ai",
    });
  } else {
    // It's a user response
    // Find the index of the last AI-generated question without an answer
    let lastAIQuestionIndex = -1;
    for (let i = parsedData.length - 1; i >= 0; i--) {
      if (parsedData[i].chaType === "ai" && !parsedData[i].answer) {
        lastAIQuestionIndex = i;
        break;
      }
    }
    console.log({ lastAIQuestionIndex })

    if (lastAIQuestionIndex !== -1) {
      // Update the last AI question object with the user's answer
      parsedData[lastAIQuestionIndex].answer = msg.answer; // Assuming msg.message contains the user's answer
     
      if(msg.answerType == "file"){
          parsedData[lastAIQuestionIndex].answer = msg.answer;
          parsedData[lastAIQuestionIndex].answerType = msg.answerType;
          parsedData[lastAIQuestionIndex].fileName = msg.fileName;
          parsedData[lastAIQuestionIndex].fileUpload = msg.fileUpload;
        }

      } else {
      // Handle cases without a preceding AI question

      // Static User input response
    console.log('ELSE PART SEDING YOU ONLY', msg);

        let lastIndex = -1;

        // Iterate through the array to find the index of the last matching object
        for (let i = 0; i < parsedData.length; i++) {
            if (parsedData[i].question === msg.question) {
            lastIndex = i;
            }
        }

        // If a match was found, replace the object at that index
        if (lastIndex !== -1) {
            parsedData[lastIndex] = msg;
        } else {
            parsedData.push({
            answer: msg.message,
            sender: "you",
        });
        }
    }

  }

  localStorage.setItem('chatData', JSON.stringify(parsedData));
}
    
    async function prepareSenderData(messageInfo) {
       
        messageInfo.template_code = window.template_code;
        clearInterval(window.intervalId);
        window.timeCounter = 0;
        const questionId = window?.questionInfo?.question_id;

        console.log("get question ::: ", messageInfo);
        console.log("get question ::: ", messageInfo.chaType);

        if(messageInfo?.chaType === 'ai') {
                const chat = window.shadow.querySelector('.cbw__chat');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'cbw__sender-msg-box';
                messageDiv.dataset.type = 'sender-msg';
                let optionsHTML = \`
                    <div class="cbw__sender-msg">
                      <p>
                        \${messageInfo?.answer}
                      </p>
                    </div>
                \`;
                messageDiv.innerHTML = optionsHTML;
                chat.appendChild(messageDiv);
                window.ws.send(JSON.stringify(messageInfo));
                window.loaderCount = window.loaderCount + 1;
                loaderDisplay();

                // commented after preview in all tab AI changes
                // broadcastMessage(JSON.stringify(messageInfo), "sendToAll");

        } else if(messageInfo.answerType === 'AI_answer_field') {

            var chat = window.shadow.querySelector('.cbw__chat');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'cbw__sender-msg-box';
            messageDiv.id = 'answer-'+ window.questionInfo?.question_id;
            if(window.questionInfo?.answerType === 'Searchable_Dropdown') {
                messageDiv.className = 'cbw__sender-msg-box text-capitalize';
            }
            messageDiv.innerHTML = '<p class="cbw__sender-msg">'+ messageInfo?.answer+ '</p>'
            chat.appendChild(messageDiv);
            setTimeout(scrollToBottom, 100);
            if(window.shadow.getElementById(questionId)) {
                window.shadow.getElementById(questionId).classList.add('pointer-event');
            }
            window.loaderCount =  window.loaderCount + 1;
            const fetchData = await fetchAIanswerData(messageInfo?.answer);
            if(fetchData) {
                const loaderId = 'main-loader-'+ window.loaderCount;
                window.shadow.getElementById(loaderId)?.classList?.add('hide');
                const questionId = window?.questionInfo?.question_id;
                var chat = window.shadow.querySelector('.cbw__chat');
                const messageDiv = document.createElement('div');

                messageDiv.id = questionId;
                messageDiv.className = 'cbw__receiver-msg-box';
                messageDiv.dataset.type = 'receiver-msg';
                let optionsHTML = \`
                    <div class="cbw__receiver-msg">
                    \${fetchData?.data?.answer}
                    </div>
                \`;
                messageDiv.innerHTML = optionsHTML;
                chat.appendChild(messageDiv);
                if(window.shadow.getElementById(questionId)) {
                    window.shadow.getElementById(questionId).classList.add('pointer-event');
                }
                messageInfo.answer = fetchData?.data?.answer;
                window.ws.send(JSON.stringify(messageInfo));
                setTimeout(scrollToBottom, 100);
                window.loaderCount = window.loaderCount + 1;
                loaderDisplay();

            }
        } else {
            var chat = window.shadow.querySelector('.cbw__chat');
            const messageDiv = document.createElement('div');
            if(messageInfo?.answerType === 'Calender') {
                messageDiv.className = 'cbw__receiver-msg-box';
            } else {
                messageDiv.className = 'cbw__sender-msg-box';
            }
            messageDiv.id = 'answer-'+ window.questionInfo?.question_id;
            if(window.questionInfo?.answerType === 'Searchable_Dropdown') {
                messageDiv.className = 'cbw__sender-msg-box text-capitalize';
            }
            if(messageInfo?.answerType === 'Calender') { 
                messageDiv.innerHTML = '<p class="cbw__receiver-msg">'+ messageInfo?.answer+ '</p>'
            } else {
                messageDiv.innerHTML = '<p class="cbw__sender-msg">'+ messageInfo?.answer+ '</p>'
            }
            const answerId =  'answer-'+ window.questionInfo?.question_id;
            if(!window.shadow.getElementById(answerId)) {
                window.ws.send(JSON.stringify(messageInfo));

                console.log("load ::: 2 prependsenddata")
                storeData(messageInfo);

                chat.appendChild(messageDiv);
                if(window.shadow.getElementById(questionId)) {
                    window.shadow.getElementById(questionId).classList.add('pointer-event');
                }
                setTimeout(scrollToBottom, 100);
                window.loaderCount = window.loaderCount + 1;
                loaderDisplay();
            }
        }
            
        appendMessageToLocalStorage(messageInfo)
    }

    window.shadow.getElementById('chat-container').addEventListener('change', (event) => {
        event.preventDefault();

        // RADIO BUTTON EVENT
        if (event?.target?.classList.contains('select-btn') && event.target.value === 'on') {
            var d = event.target.id;
            broadcastMessage(event.target.id, "radioChangeEvent");
            const splitData = d.split('-');
            var selectedId = splitData[1];
            var selectedMsg = window.questionInfo?.answers?.[0]?.paramValue?.[selectedId]?.value;
            var selectedMsgId = window.questionInfo?.answers?.[0]?.paramValue?.[selectedId]?.id;

            const messageJson = {
                sender: 'you',
                question:  window.questionInfo?.question,
                answerType: window?.questionInfo?.answerType,
                question_id: window.questionInfo?.question_id,
                questionId: window.questionInfo?.questionId,
                roomKey: window.roomKey,
                answer: selectedMsg,
                answerOption:selectedMsgId,
                timeout: Date.now(),
                referenceName:  window.questionInfo?.referenceName,
                uuid: window.questionInfo?.uuid,
                templateId: window?.questionInfo?.templateId,
                tenantId: window?.questionInfo?.tenantId,
                userUUID: window.questionInfo?.userUUID,
                ideal: false,
            };
            prepareSenderData(messageJson);
        }
        
        if (event.target.classList.contains('dropdown') && event.target.value !== '') {
            var selectedId = event.target.value;
            broadcastMessage(event.target.id, "dropDownChangeEvent");
            var selectedMsg = window.questionInfo?.answers[0]?.paramValue?.[selectedId]?.value;
            const messageJson = {
                sender: 'you',
                question:  window.questionInfo?.question,
                answerType: window?.questionInfo?.answerType,
                question_id: window.questionInfo?.question_id,
                questionId: window.questionInfo.questionId,
                roomKey: window.roomKey,
                answer: selectedMsg,
                answerOption: selectedId,
                timeout: Date.now(),
                referenceName:  window.questionInfo?.referenceName,
                uuid: window.questionInfo?.uuid,
                templateId: window?.questionInfo?.templateId,
                tenantId: window?.questionInfo?.tenantId,
                userUUID: window.questionInfo?.userUUID,
                ideal: false,
            };
            prepareSenderData(messageJson);
        }
    });

//     function prepareFileUploadMessage({ fileName, uploadStatus, fileUrl }){
//     const chat = window.shadow.querySelector('.cbw__chat');
    
//     if (uploadStatus === "UPLOADING") {

//         // Create a new message with the spinner icon

//         const fileMsgDiv = document.createElement('div');
//         fileMsgDiv.className = 'cbw__sender-file-msg-box';
        
//         const fileUploadDiv = \`
//             <div class="cbw__sender-file-msg">
//                 <span id="file-upload-loader">
//                     <svg width="16" height="16" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 3px; margin-right: 5px">
//                         <style>.spinner_Wezc{transform-origin:center;animation:spinner_Oiah .75s step-end infinite}@keyframes spinner_Oiah{8.3%{transform:rotate(30deg)}16.6%{transform:rotate(60deg)}25%{transform:rotate(90deg)}33.3%{transform:rotate(120deg)}41.6%{transform:rotate(150deg)}50%{transform:rotate(180deg)}58.3%{transform:rotate(210deg)}66.6%{transform:rotate(240deg)}75%{transform:rotate(270deg)}83.3%{transform:rotate(300deg)}91.6%{transform:rotate(330deg)}100%{transform:rotate(360deg)}}</style>
//                         <g class="spinner_Wezc" fill="#1264E2">
//                             <circle cx="12" cy="2.5" r="1.5" opacity=".14"/>
//                             <circle cx="16.75" cy="3.77" r="1.5" opacity=".29"/>
//                             <circle cx="20.23" cy="7.25" r="1.5" opacity=".43"/>
//                             <circle cx="21.50" cy="12.00" r="1.5" opacity=".57"/>
//                             <circle cx="20.23" cy="16.75" r="1.5" opacity=".71"/>
//                             <circle cx="16.75" cy="20.23" r="1.5" opacity=".86"/>
//                             <circle cx="12" cy="21.5" r="1.5"/>
//                         </g>
//                     </svg>
//                 </span> 
//                 \${fileName}
//             </div>
//         \`;
        
//         fileMsgDiv.innerHTML = fileUploadDiv;
//         chat.appendChild(fileMsgDiv);
        
//     } else if (uploadStatus === "UPLOADED") {
//         // Find and remove the loader element

//         const loader = window.shadow.getElementById('file-upload-loader');
        
//         if (loader) {
//             loader.remove();
//         }

//         const fileMsgElement = window.shadow.querySelector('.cbw__sender-file-msg');
        
//         if (fileUrl) {
            
//             if (fileMsgElement) {
//                 fileMsgElement.style.cursor = 'pointer';
//                 fileMsgElement.addEventListener('click', () => {
//                     window.open(fileUrl, '_blank');
//                 });
//             }
//         }


//         // append download icon

//         const downloadSvgContainer = document.createElement('div');

//         downloadSvgContainer.style.marginTop = '6px';
//         downloadSvgContainer.style.marginLeft = '10px';
//         downloadSvgContainer.style.display = 'inline-block'; // To align with text
//         downloadSvgContainer.style.verticalAlign = 'middle';

//         downloadSvgContainer.innerHTML = \`
//             <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
//                 <path d="M1 13C1 15.8284 1 17.2426 1.87868 18.1213C2.75736 19 4.17157 19 7 19H13C15.8284 19 17.2426 19 18.1213 18.1213C19 17.2426 19 15.8284 19 13" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
//                 <path d="M10 1L10 14M10 14L6 9.625M10 14L14 9.625" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
//             </svg>
//         \`

//         fileMsgElement.appendChild(downloadSvgContainer)
//     }
// }

function prepareFileUploadMessage({ fileName, uploadStatus, fileUrl }) {
    const chat = window.shadow.querySelector('.cbw__chat');
    
    if (uploadStatus === "UPLOADING") {
        // Create a new message with the spinner icon
        const fileMsgDiv = document.createElement('div');
        fileMsgDiv.className = 'cbw__sender-file-msg-box';
        
        const fileUploadDiv = \`
            <div class="cbw__sender-file-msg">
                <span class="file-upload-loader">
                    <svg width="16" height="16" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 3px; margin-right: 5px">
                        <style>.spinner_Wezc{transform-origin:center;animation:spinner_Oiah .75s step-end infinite}@keyframes spinner_Oiah{8.3%{transform:rotate(30deg)}16.6%{transform:rotate(60deg)}25%{transform:rotate(90deg)}33.3%{transform:rotate(120deg)}41.6%{transform:rotate(150deg)}50%{transform:rotate(180deg)}58.3%{transform:rotate(210deg)}66.6%{transform:rotate(240deg)}75%{transform:rotate(270deg)}83.3%{transform:rotate(300deg)}91.6%{transform:rotate(330deg)}100%{transform:rotate(360deg)}}</style>
                        <g class="spinner_Wezc" fill="#1264E2">
                            <circle cx="12" cy="2.5" r="1.5" opacity=".14"/>
                            <circle cx="16.75" cy="3.77" r="1.5" opacity=".29"/>
                            <circle cx="20.23" cy="7.25" r="1.5" opacity=".43"/>
                            <circle cx="21.50" cy="12.00" r="1.5" opacity=".57"/>
                            <circle cx="20.23" cy="16.75" r="1.5" opacity=".71"/>
                            <circle cx="16.75" cy="20.23" r="1.5" opacity=".86"/>
                            <circle cx="12" cy="21.5" r="1.5"/>
                        </g>
                    </svg>
                </span> 
                \${ellipsizeFilename(fileName)}
            </div>
        \`;
        
        fileMsgDiv.innerHTML = fileUploadDiv;
        chat.appendChild(fileMsgDiv);

        // disable file upload in the mean time

        const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
        fileUploadBtn.style.cursor =  'not-allowed';
        fileUploadBtn.disabled = true;    
        
        // disable input in the mean time

        const inputBox = window.shadow.getElementById('messageInput');
        inputBox.style.cursor =  'progress';
        inputBox.disabled = true;      
        
    } else if (uploadStatus === "UPLOADED") {
        // Get all file message boxes and select the last one
        const allFileMessages = window.shadow.querySelectorAll('.cbw__sender-file-msg-box');
        const lastFileBox = allFileMessages[allFileMessages.length - 1];
        
        if (!lastFileBox) return;
        
        // Find the loader in the last file box
        const loader = lastFileBox.querySelector('.file-upload-loader');
        if (loader) {
            loader.remove();
        }
        
        // Get the message element from the last file box
        const fileMsgElement = lastFileBox.querySelector('.cbw__sender-file-msg');
        
        if (fileMsgElement && fileUrl) {
            fileMsgElement.style.cursor = 'pointer';
            fileMsgElement.addEventListener('click', () => {
                window.open(fileUrl, '_blank');
            });
            
            // Check if download icon already exists
            const existingIcon = fileMsgElement.querySelector('.download-icon');
            if (!existingIcon) {
                // Append download icon
                const downloadSvgContainer = document.createElement('div');
                downloadSvgContainer.className = 'download-icon';
                downloadSvgContainer.style.marginTop = '6px';
                downloadSvgContainer.style.marginLeft = '10px';
                downloadSvgContainer.style.display = 'inline-block'; // To align with text
                downloadSvgContainer.style.verticalAlign = 'middle';
                
                downloadSvgContainer.innerHTML = \`
                    <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M1 13C1 15.8284 1 17.2426 1.87868 18.1213C2.75736 19 4.17157 19 7 19H13C15.8284 19 17.2426 19 18.1213 18.1213C19 17.2426 19 15.8284 19 13" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M10 1L10 14M10 14L6 9.625M10 14L14 9.625" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                \`;
                
                fileMsgElement.appendChild(downloadSvgContainer);
            }
        }

        // enable file upload button once file uploaded

        const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
        fileUploadBtn.style.cursor =  'pointer';
        fileUploadBtn.disabled = false;  

        // enable input once file uploaded

        const inputBox = window.shadow.getElementById('messageInput');
        inputBox.style.cursor =  'text';
        inputBox.disabled = false; 
    }

    else if(uploadStatus === "LOAD_FROM_HISTORY"){

      const fileMessageDiv = \`
        <div class="cbw__sender-file-msg-box" style="cursor: pointer;" onclick="window.open('\${fileUrl}', '_blank')">
            <div class="cbw__sender-file-msg">
                \${ellipsizeFilename(fileName)}
                <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-left: 10px">
                    <path d="M1 13C1 15.8284 1 17.2426 1.87868 18.1213C2.75736 19 4.17157 19 7 19H13C15.8284 19 17.2426 19 18.1213 18.1213C19 17.2426 19 15.8284 19 13" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M10 1L10 14M10 14L6 9.625M10 14L14 9.625" stroke="#1264E2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
        </div>
      \`

      return fileMessageDiv;
    }

    function ellipsizeFilename(filename) {
        const FILE_CHAR_LENGTH_FOR_ELLIPSE = 22
        if (filename.length <= FILE_CHAR_LENGTH_FOR_ELLIPSE) {
            return filename;
        }
        
        // Split the filename to preserve the extension
        const lastDotIndex = filename.lastIndexOf('.');
        let name, extension;
        
        if (lastDotIndex === -1) {
            name = filename;
            extension = '';
        } else {
            name = filename.substring(0, lastDotIndex);
            extension = filename.substring(lastDotIndex);
        }
        
        // Calculate how many characters to keep on each side
        const charsToKeep = Math.floor((18 - 3) / 2); // 21 - 3(for '...') = 18, then divide by 2
        const start = name.substring(0, charsToKeep);
        const end = name.substring(name.length - charsToKeep);
        
        return start + '...' + end + extension;
    }

}
 
    
    function isCalendlyEvent(e) {
        return e.origin === "https://calendly.com" && e.data.event && e.data.event.indexOf("calendly.") === 0;
    };

    function loadAiCalendly() {
        let questionId = 'calendar1';
        
        if(window.calendlyUrl) {
           const questionIdD = 'calendar1';

            // window.calendlyLink += window.calendlyUrl + '?embed_domain='+window.url.host+ '&embed_type=Inline&hide_gdpr_banner=1&hide_event_type_details=1&hide_landing_page_details=1';
            window.calendlyLink += window.calendlyUrl + '?embed_domain='+window.url.host+ '&embed_type=Inline&hide_gdpr_banner=1&hide_event_type_details=1&hide_landing_page_details=1' + '&name=' + window.calendlyName + '&email=' + window.calendlyEmail;
    
            const calendlyContainer = document.createElement('div');
            calendlyContainer.id = questionId;
            var chat = window.shadow.querySelector('.cbw__chat');
            var chatCalendar = window.shadow.querySelector('.cbw__chat__calendar');
            if (window.shadow.getElementById(questionId)) {
                const parentElement = window.shadow.getElementById(questionId);
                parentElement.remove();
            }
            chatCalendar.append(calendlyContainer);

            setTimeout(() => {
                chatCalendar.style.display = 'block';
                chat.style.display = 'none';

                const inputBox = window.shadow.querySelector(".cbw__footer");
                inputBox.classList.remove('show');
                inputBox.classList.add('hide');                
            }, 1000);
            
            const calendlyLinkScript =  document.createElement('script');
            calendlyLinkScript.innerHTML += \`Calendly.initInlineWidget({
                url: window.calendlyLink,
                parentElement: window.shadow.getElementById('calendar1'),
                resize: true
            });\`
            
            window.shadow.appendChild(calendlyLinkScript);
            setTimeout(scrollToBottom, 100);
            const elements = window.shadow.querySelectorAll('iframe');
            elements.forEach(element => {
                element.setAttribute('style', 'min-height: 0px !important;');
            });

            // to ensure singleton listener of calendly
            if (window.__calendlyListenerAttached) return;

            window.addEventListener("message", function(e) {
                if(isCalendlyEvent(e)) {
                    if (e.data.event && e.data.event === 'calendly.event_scheduled') {
                        const selectedDate = event.data.event.start_time;
                        const messageJson = {
                            sender: 'you',
                            question:  "Completed.",
                            roomKey: window.roomKey,
                            answer: "Booked.",
                            // answer: "Completed.",
                            timeout: Date.now(),
                            // uuid: window.questionInfo?.uuid,
                            // templateId: window?.questionInfo?.templateId,
                            // tenantId: window?.questionInfo?.tenantId,
                            // userUUID: window.questionInfo?.userUUID,
                            // ideal:false,
                        };
                        // prepareSenderData(messageJson);

                        window.ws.send(JSON.stringify(messageJson));

                        window.loaderCount = window.loaderCount + 1;
                        loaderDisplay();                        

                        var chat = window.shadow.querySelector('.cbw__chat');
                        var chatCalendar = window.shadow.querySelector('.cbw__chat__calendar');
                        chatCalendar.style.display = 'none';
                        chat.style.display = 'flex';
                        const calendlyId = 'calendly-'+ window?.questionInfo?.question_id;
                        window.shadow.getElementById(calendlyId).classList.add('pointer-event');
                        // calendlyId.classList.add('pointer-event');
                    }
                    /* Example to get the name of the event */
                    
                    /* Example to get the payload of the event */
                }
            });
            window.__calendlyListenerAttached = true;
        }
    }

    function loadCalendly() {
        let questionId = 'calendar' + window.questionInfo?.question_id;
        // window.questionInfo.schedulingUrl = window.calendlyL;
        if(window?.questionInfo?.schedulingUrl) {
           const questionIdD = 'calendar' + window.questionInfo?.question_id;

            window.calendlyLink += questionInfo?.schedulingUrl + '?embed_domain='+window.url.host+ '&embed_type=Inline&hide_gdpr_banner=1&hide_event_type_details=1&hide_landing_page_details=1';
            // if (window.shadow.getElementById(questionId)) {
            //     return;
            // }
            if(window.questionInfo?.calendlyData?.length > 0) {
                const getFirstName = window.questionInfo?.calendlyData.filter((item) => item.referenceName === 'first_name');
                let name = '';
                if(getFirstName?.length> 0) {
                    name += '&name=' + getFirstName[0]?.answer?.replace(/['"]+/g, '');
                }
                const getLastName = window.questionInfo?.calendlyData.filter((item) => item.referenceName === 'last_name');
                if(getLastName?.length > 0) {
                    name += ' ' + getLastName?.[0]?.answer?.replace(/['"]+/g, '');
                }
                window.calendlyLink += name;
                const getEmail = window.questionInfo?.calendlyData.filter((item) => item.referenceName === 'email');
                if(getEmail?.length > 0) {
                    window.calendlyLink += '&email=' + getEmail?.[0]?.answer?.replace(/['"]+/g, '');
                }
           }
            const calendlyContainer = document.createElement('div');
            calendlyContainer.id = questionId;
            var chat = window.shadow.querySelector('.cbw__chat');
            var chatCalendar = window.shadow.querySelector('.cbw__chat__calendar');
            if (window.shadow.getElementById(questionId)) {
                const parentElement = window.shadow.getElementById(questionId);
                parentElement.remove();
            }
            chatCalendar.append(calendlyContainer);
            setTimeout(() => {
                chatCalendar.style.display = 'block';
                chat.style.display = 'none';
            }, 1000);
            const calendlyLinkScript =  document.createElement('script');
            calendlyLinkScript.innerHTML += \`Calendly.initInlineWidget({
                url: window.calendlyLink,
                parentElement: window.shadow.getElementById('calendar' + window.questionInfo?.question_id),
                resize: true
            });\`
            
            window.shadow.appendChild(calendlyLinkScript);
            setTimeout(scrollToBottom, 100);
            const elements = window.shadow.querySelectorAll('iframe');
            elements.forEach(element => {
                element.setAttribute('style', 'min-height: 0px !important;');
            });

            // to ensure singleton listener of calendly
            if (window.__calendlyListenerAttached) return;
                        
            window.addEventListener("message", function(e) {
                if(isCalendlyEvent(e)) {
                    if (e.data.event && e.data.event === 'calendly.event_scheduled') {
                        const selectedDate = event.data.event.start_time;
                        const messageJson = {
                            sender: 'you',
                            question:  window.questionInfo?.question,
                            answerType: window?.questionInfo?.answerType,
                            question_id: window.questionInfo?.question_id,
                            questionId: window.questionInfo.questionId,
                            roomKey: window.roomKey,
                            answer: "Meeting booked successfully!",
                            answerOption: e.data.payload,
                            timeout: Date.now(),
                            referenceName:  window.questionInfo?.referenceName,
                            uuid: window.questionInfo?.uuid,
                            templateId: window?.questionInfo?.templateId,
                            tenantId: window?.questionInfo?.tenantId,
                            userUUID: window.questionInfo?.userUUID,
                            ideal:false,
                        };
                        prepareSenderData(messageJson);
                        var chat = window.shadow.querySelector('.cbw__chat');
                        var chatCalendar = window.shadow.querySelector('.cbw__chat__calendar');
                        chatCalendar.style.display = 'none';
                        chat.style.display = 'flex';
                        const calendlyId = 'calendly-'+ window?.questionInfo?.question_id;
                        window.shadow.getElementById(calendlyId).classList.add('pointer-event');
                        // calendlyId.classList.add('pointer-event');
                    }
                    /* Example to get the name of the event */
                    
                    /* Example to get the payload of the event */
                }
            });
            window.__calendlyListenerAttached = true;
        }
    }

    
    function nextQuestionPrepare(info) {
        var chat = window.shadow.querySelector('.cbw__chat');
        const loaderId = 'loader-' + window?.questionInfo?.question_id;       

        console.log("=======================", info)

        if(window?.questionInfo?.answerType !== 'End_Chat' && window?.questionInfo?.answerType !== 'No_Answer' && window?.questionInfo?.answerType !== 'Close_Tab') {
            
                if(window?.questionInfo?.answerType !== 'End_Chat' &&  window?.questionInfo?.answerType !== 'No_Answer' && window?.questionInfo?.answerType !== 'Close_Tab') {
                    if( window.shadow.getElementById(loaderId)) {
                        window.shadow.getElementById(loaderId).classList.add('hide');
                    }
                    if( window?.questionInfo?.answerType !== 'Calender' ) {
                        tempContainer = getQuestionData(info?.answerType ,info?.answers?.[0]?.paramValue, info?.answers?.[0]?.hyperLink, info, info?.questions?.[0]?.formTitle);
                        chat.append(tempContainer);
                        setTimeout(scrollToBottom, 100);
                        chat.scrollTop = chat.scrollHeight;
                    }
                    var inputBox = window.shadow.querySelector(".cbw__footer");
                    if(window.questionInfo?.answerType === 'Input_box') {
                        if(inputBox) {
                            inputBox.classList.remove('hide');
                            inputBox.classList.add('show');
                        }
                            
                        const fileUploadBtn = window.shadow.querySelector('.cbw__attachement-btn');
                        
                        if(fileUploadBtn){
                            fileUploadBtn.style.cursor =  'not-allowed';
                            fileUploadBtn.disabled = true;   
                        }                               
                    } else if (window.questionInfo?.answerType === 'File_Upload') {
                        if(inputBox) {
                            inputBox.classList.remove('hide');
                            inputBox.classList.add('show');

                            // enable input once file uploaded

                            const input = window.shadow.getElementById('messageInput');
                            // input.style.cursor =  'text';
                            // input.disabled = false;                              
                            input.style.cursor = "not-allowed";
                            input.disable = true;
                        }
                    } else {
                        inputBox.classList.remove('show');
                        inputBox.classList.add('hide');
                    }
                    if(window.questionInfo?.answerType === 'Searchable_Dropdown') {
                        loadDropdown(info?.answers[0]?.paramValue);
                    } 
                    if(window.questionInfo?.answerType === 'AI_answer_field') {
                        var inputBox = window.shadow.querySelector(".cbw__footer");

                        inputBox.classList.remove('hide');
                            inputBox.classList.add('show');
                    }
                            
                    if(window.questionInfo?.answerType === 'Calender') {

                        let linkCalendarData = "";
                        if((info?.answers?.[0]?.hyperLink).length > 0){

                            const linkUrl =  info?.answers?.[0]?.hyperLink[0]?.url;
                            const linkText =  info?.answers?.[0]?.hyperLink[0]?.textToBeLinked;
                            linkCalendarData += '<span>' ;
                            linkCalendarData += window.questionInfo?.question.replace(linkText, ' <a class="calendly-btn" href="' + linkUrl + '" target="_blank">' + linkText + '</a>');
                            linkCalendarData += '<\span>' ;

                        } else {
                            linkCalendarData = window.questionInfo?.question;
                        }

                        // let questionId = 'calendar' + window.questionInfo?.question_id;
                        var chat = window.shadow.querySelector('.cbw__chat');
                        var tempContainer = document.createElement('div');
                        tempContainer.className = 'cbw__receiver-msg-box';
                        tempContainer.style.position = 'relative'; 
                        // tempContainer.id = questionId;
                        tempContainer.innerHTML += \`<div class="" data-type="receiver-msg">
                            <p class="cbw__receiver-msg">
                            \${linkCalendarData}
                            </p>
                        </div>\`;
                        setTimeout(scrollToBottom, 100);
                        chat.appendChild(tempContainer);
                        const calendlyId = 'calendly-'+ window?.questionInfo?.question_id;
                        var tempContainerD = document.createElement('div');
                        tempContainerD.className = 'cbw__receiver-msg-box';
                        tempContainerD.id = window?.questionInfo?.question_id;
                        tempContainerD.innerHTML += \`
                        <div class="cbw__receiver-msg">
                            <button class="calendly-btn" onclick="loadCalendly()" id="\${calendlyId}">
                            Choose Time
                            </button>
                        </div>
                        \`;
                        // \`;
                       
                        chat.appendChild(tempContainerD);
                    }
                  
                }
            // }, 1000); // 1000 milliseconds = 1 seconds
        } else if(window?.questionInfo?.answerType === 'No_Answer' || window?.questionInfo?.answerType === 'End_Chat' ) {
            tempContainer = getQuestionData(info?.answerType ,info?.answers?.[0]?.paramValue, info?.answers?.[0]?.hyperLink,[]);
            chat.append(tempContainer);
            var inputBox = window.shadow.querySelector(".cbw__footer");
            inputBox.classList.remove('show');
            inputBox.classList.add('hide');
        }
       
        
    };`;
window.shadow.appendChild(messageSendScript);
const dropdownScript = document.createElement("script");
dropdownScript.innerHTML += `
    function scrollToBottom() {
        var chatDiv = window.shadow.querySelector('.cbw__chat');
        chatDiv.scrollTop = chatDiv.scrollHeight;
        chatDiv.scrollTo(0,chatDiv.scrollHeight);

    }
    function loadDropdown(data) {
        var dropdownContainer = document.createElement('div');
        dropdownContainer.id = window?.questionInfo?.question_id;
        dropdownContainer.className = 'custom-select';
        let HTMLdata = \`
                    <select id="dropdown" class="dropdown">
                    <option value="" class="dropdown-option-btn">Select</option>
                \`;
        for(let i = 0; i < data.length; i++) {
            HTMLdata += \`
                <option value="\${i}" class="dropdown-option-btn">
                    \${data[i].value}
                </option>
            \`;
        }
        HTMLdata += \`
                    </select>
        \`;
        dropdownContainer.innerHTML = HTMLdata;
        var chat = window.shadow.querySelector('.cbw__chat');
        chat.append(dropdownContainer);
        setTimeout(scrollToBottom, 100);
        var questionId = window?.questionInfo?.question_id;
        var selector = '[id="' + questionId + '"] .custom-select';

        var parentDiv = window.shadow.getElementById(window?.questionInfo?.question_id);
        var x = 0;
        if (parentDiv) {
            // var x = document.getElementsByClassName("custom-select");
            var x = window.shadow.querySelector(".custom-select");
        }

        // if(x?.length > 0) {

        if(x) {
            
            var x, i, j, l, ll, selElmnt, a, b, c;
            
            /* Look for any elements with the class "custom-select": */
            // x = document.getElementsByClassName("custom-select");
            x = window.shadow.querySelector(".custom-select");
            
            l = x.length;
            // for (i = 0; i < l; i++) {

                selElmnt = parentDiv.getElementsByTagName("select")[0];
                ll = selElmnt.length;
                /* For each element, create a new DIV that will act as the selected item: */
                a = document.createElement("DIV");
                a.setAttribute("class", "select-selected");
                const selectedSelectId = 'select-selected' + questionId;
                a.setAttribute("id", selectedSelectId);
                a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
                parentDiv.appendChild(a);
                /* For each element, create a new DIV that will contain the option list: */
                b = document.createElement("DIV");
                b.setAttribute("class", "select-items select-hide");
                for (var j = 1; j < ll; j++) {
                    /* For each option in the original select element,
                    create a new DIV that will act as an option item: */
                    c = document.createElement("DIV");
                    c.innerHTML = selElmnt.options[j].innerHTML;
                    c.addEventListener("click", function(e) {
                    /* When an item is clicked, update the original select box,
                    and the selected item: */
                    var y, i, k, s, h, sl, yl;
                    s = this.parentNode.parentNode.getElementsByTagName("select")[0];
                    sl = s.length;
                    h = this.parentNode.previousSibling;
                    for (i = 0; i < sl; i++) {
                        if (s.options[i].innerHTML == this.innerHTML) {
                            s.selectedIndex = i;
                            h.innerHTML = this.innerHTML;
                            y = this.parentNode.getElementsByClassName("same-as-selected");
                                    yl = y.length;
                                    for (k = 0; k < yl; k++) {
                                    y[k].removeAttribute("class");
                                    }
                                    this.setAttribute("class", "same-as-selected");
                                    break;
                                }
                            }
                            h.click();
                        });
                        b.appendChild(c);
                    }
                    parentDiv.appendChild(b);
                    a.addEventListener("click", function(e) {
                        /* When the select box is clicked, close any other select boxes,
                        and open/close the current select box: */
                        e.stopPropagation();
                        closeAllSelect(this);
                        var myDiv = window.shadow.querySelector('.select-selected');
                        const selectedSelectId = 'select-selected' + questionId;
                        var myDiv = window.shadow.querySelector("#" + selectedSelectId);

                        // for (var i = 0; i < myDiv.length; i++) {
                            var selectedMsg = myDiv.textContent;
                            var selectedId = window.questionInfo?.answers?.[0]?.paramValue?.filter((item) => item.value.trim() === selectedMsg?.trim() );
                            if(selectedId?.length > 0) {

                                broadcastMessage(selectedMsg.trim() + "-"+ questionId, "dropDownChangeEvent");

                                const messageJson = {
                                    sender: 'you',
                                    question:  window.questionInfo?.question,
                                    answerType: window?.questionInfo?.answerType,
                                    question_id: window.questionInfo?.question_id,
                                    questionId: window.questionInfo.questionId,
                                    roomKey: window.roomKey,
                                    answer: selectedMsg.trim(),
                                    answerOption: selectedId?.[0]?.id,
                                    timeout: Date.now(),
                                    referenceName:  window.questionInfo?.referenceName,
                                    uuid: window.questionInfo?.uuid,
                                    templateId: window?.questionInfo?.templateId,
                                    tenantId: window?.questionInfo?.tenantId,
                                    userUUID: window.questionInfo?.userUUID,
                                    ideal: false,
                                
                                };
                                prepareSenderData(messageJson);
                            }
                        // }
                        this.nextSibling.classList.toggle("select-hide");
                        this.classList.toggle("select-arrow-active");
                        chat.scrollTop = chat.scrollHeight;

                    });
                }
        // }
    }

    function closeAllSelect(elmnt) {
        var parentDiv = window.shadow.getElementById(window?.questionInfo?.question_id);

        /* A function that will close all select boxes in the document,
        except the current select box: */
        var x, y, i, xl, yl, arrNo = [];
        x = document.getElementsByClassName("select-items");
        y = document.getElementsByClassName("select-selected");
        xl = x.length;
        yl = y.length;
        for (i = 0; i < yl; i++) {
            if (elmnt == y[i]) {
                arrNo.push(i)

            } else {
                y[i].classList.remove("select-arrow-active");
            }
        }
        for (i = 0; i < xl; i++) {
            if (arrNo.indexOf(i)) {
                // parentDiv.classList.add("select-hide");
            }
        }
        
    }
    `;
window.shadow.appendChild(dropdownScript);
});