/*
 * Developed as part of SM-6273 - Integrate with Connect AI Support Assistant for custom UI
 **/

function checkBotHistory(){
    try {
        return (sessionStorage.getItem('VA_Details') && JSON.parse(sessionStorage.getItem('VA_Details'))['ab57fd0432e25d5b3013133a1c910d56']['messages'].length > 0);
    } catch (error){
        return false;
    }
}

if (checkBotHistory()){
    var myvar = '<html>' +
                '<head>' +
                '</head>' +
                '<body>' +
                '     <connect-ai-widget></connect-ai-widget> ' +
                '</body>' +
                '</html>';
    document.write(myvar);
    window.vaConfig ={
        "autoOpen": false
    }
    // document.dispatchEvent(new CustomEvent('updateVADetails', { detail: { data: true}})) 
    const el = document.querySelector('connect-ai-widget');
    if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
    if(el) el.setAttribute("config", JSON.stringify(window.vaConfig));
} else {
    setTimeout(function(){
        let body = (document.getElementsByTagName('body').length > 0) ? document.getElementsByTagName('body')[0] : document.createElement('body');
        let element = document.createElement('div');
        element.innerHTML = '<button class="demo-myvm-chat-button" onclick=initiateVirtualAssistant() style="height:auto!important;position:fixed;bottom:65px;right:30px;z-index:1000;overflow:visible;overflow:initial;cursor:pointer;padding:0!important;margin:0!important;border:none!important;background:0 0!important;box-shadow:none!important;height:auto!important;position:fixed;bottom:65px;right:30px;z-index:1000;overflow:visible;overflow:initial;cursor:pointer;padding:0!important;margin:0!important;border:none!important;background:0 0!important;box-shadow:none!important"tabindex=0><div style="display:flex;flex-direction:row;justify-content:center;align-items:center;text-transform:none!important;color:#fff;position:relative;padding:0 18px;height:40px;background:#254385;border-radius:60px;-moz-border-radius:60px;-webkit-border-radius:60px"><span stlye="display: inline-flex;"><svg height=22 preserveAspectRatio="xMidYMid meet"style=fill:#fff version=1.1 viewBox="0 0 36 36"width=22 xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink><path _ngcontent-jqk-c96=""class="clr-i-solid clr-i-solid-path-1"d=M23.86,29.15H12.11a.8.8,0,1,0,0,1.6H23.86a.8.8,0,0,0,0-1.6Z></path><path _ngcontent-jqk-c96=""class="clr-i-solid clr-i-solid-path-2"d=M22,32.15H14a.8.8,0,1,0,0,1.6H22a.8.8,0,1,0,0-1.6Z></path><path _ngcontent-jqk-c96=""class="clr-i-solid clr-i-solid-path-3"d=M18,2.25a11,11,0,0,0-11,11,10.68,10.68,0,0,0,1,4.63,16.36,16.36,0,0,0,1.12,1.78,17,17,0,0,1,2,3.47,16.19,16.19,0,0,1,.59,4h5.69V21.61l-2.86-3.13,3-3a.8.8,0,0,1,1.13,1.13l-1.89,1.89L19,21v6.17H24.3a16.19,16.19,0,0,1,.59-4,17,17,0,0,1,2-3.47A16.31,16.31,0,0,0,28,17.86a10.68,10.68,0,0,0,1-4.63A11,11,0,0,0,18,2.25ZM18.45,12l-2.73,2.73a.8.8,0,1,1-1.13-1.13l2.73-2.73A.8.8,0,1,1,18.45,12Z></path><rect fill-opacity=0 height=36 width=36 x=0 y=0></rect></svg> </span><span style="padding-left:7px;font-size:16px;line-height:18px;white-space:nowrap" class="demo-va-chat-bubble-text slds-no-print">Support Assistant</span></div></button>';
        body.appendChild(element);
        document.getElementsByTagName('html')[0].appendChild(body);    
    }, 2000);
}

function initiateVirtualAssistant() {
    document.getElementsByClassName('demo-myvm-chat-button')[0].remove();
    let body = document.getElementsByTagName('body');
    body[0].appendChild(document.createElement("connect-ai-widget"));
    refreshAuthToken = true;
    //vaAuthToken();
    window.vaConfig ={
        "launcherText": portallanguage,
        "autoOpen": true
    }
    const el = document.querySelector('connect-ai-widget');
    if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
    if(el) el.setAttribute("config", JSON.stringify(window.vaConfig));
    // document.dispatchEvent(new CustomEvent('updateVADetails', { detail: { data: true}})) 
}

var currentPageUrl = window.location.hostname;
var baseURL;
var aiseraBotLaunchButton = false;

window.aisera_bot = {};
window.aisera_bot.url = window.location.href;
var s;
var botLoaded = false;
var isArticleDetailPage = (window.location.href.indexOf("/s/article/") !== -1);
var aiseraBotLaunchButton = false;
var portallanguage = 'Support Assistant';
var userDetails;

if (currentPageUrl.includes("gslint") || currentPageUrl.includes("gslqa") || currentPageUrl.includes("kb-uat")) {
    baseURL = "https://apigw-test.vmware.com/uat2/v1/m4/api/connectai";
}
else if (currentPageUrl.includes("gslstage")) {
    baseURL = "https://apigw-test.vmware.com/stg/v1/m4/api/connectai";
}
else {
    baseURL = "https://apigw.vmware.com/v1/m4/api/connectai";
}
window.vaData = {
    userInfo: {
        name: "",
        email: "",
        locale: "",
        company: "N/A",
    },
    contextInfo: generateContextInfo(),
    baseUrl: baseURL,
    integrationId: "ab57fd0432e25d5b3013133a1c910d56"
};
//language Selector listner
var language='';
let languageChnange = false;
document.addEventListener("ccCustomEvent",function(event){
    if(event.detail.langObj){
    language =  event.detail.langObj.locale;
    selectedLanguage(language);
    }
});
function selectedLanguage(language){
    var iconText ='';
    if(language == 'us' || language == ''){
        iconText = 'Support Assistant';
    }else if(language == 'cn'){
        iconText = 'Support Assistant';
    }
    else if(language == 'fr'){
        iconText = 'Assistant support';
    }
    else if(language == 'de'){
        iconText = 'Support Assistant';
    }
    else if(language == 'jp'){
        iconText = 'サポート アシスタント';
    }
    window.vaConfig ={
        "launcherText": iconText
    }
    portallanguage = iconText;
    const el = document.querySelector('connect-ai-widget');
    if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
    if(el) el.setAttribute("config", JSON.stringify(window.vaConfig));
    //document.dispatchEvent(new CustomEvent('updateVADetails', { detail: { data: true}}));
    let staticButton = document.getElementsByClassName('demo-va-chat-bubble-text');
    if(staticButton != null && staticButton.length > 0 ){
        staticButton[0].innerHTML = portallanguage;
    }
}

// Event listner for VA refresh token, on event fire get the token generate/refresh and save into sessionStorage
document.addEventListener("vaRefreshToken", (event) => {
    vaAuthToken();
});

function vaAuthToken(jwtToken) {
    let connectAISession = sessionStorage.getItem('connectAIToken');
    let apiUrl;
    if (currentPageUrl.includes("gslint") || currentPageUrl.includes("gslqa") || currentPageUrl.includes("gslstage")) {
        apiUrl = "/kb/services/apexrest/ConnectAI/";
    } else {
        apiUrl = "/services/apexrest/ConnectAI/";
    }
    const httpOptions = {
        method: 'GET'
    };
    if (connectAISession != null) {
        let token = JSON.parse(connectAISession);
        let tokenExpiresIn = new Date(token.tokenExpiry).getTime();
        let curentTime = new Date().getTime();
        let remainingtime = (tokenExpiresIn - curentTime)/(1000);
        if(remainingtime > 30){
            const el = document.querySelector('connect-ai-widget');
            if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
            // document.dispatchEvent(new CustomEvent('vaTokenUpdated', { detail: { data: true } }));
            return
        }
    }
    fetch(apiUrl, httpOptions)
    .then(response => response.json())
    .then(data => {
        sessionStorage.setItem('connectAIToken', JSON.stringify(data));
        sessionStorage.setItem('vaAuthToken', data.access_token);
        const el = document.querySelector('connect-ai-widget');
        if(el) el.setAttribute("tokenUpdated", true);
        //document.dispatchEvent(new CustomEvent('vaTokenUpdated', { detail: { data: true } }));
    })
    .catch((error) => { console.error('Error:', error) });
}
//SM-6266 Adobe analytics tracking: START
const el = document.querySelector('connect-ai-widget');
if(el) {
        el.addEventListener("onOpen", (event) => {
        if (aiseraBotLaunchButton) {
            aiseraBotLaunchButton = false;
            return;
        }
        customAdobeTracking("AISERA BOT: OPENED");
    });
}
 
if(el) {
    el.addEventListener('OnClose', (event) => {
        customAdobeTracking("AISERA BOT: CLOSED");
    })
}
 
if(el) {
    el.addEventListener('onMinimise', (event) => {
        customAdobeTracking("AISERA BOT: MINIMISED");
    })
}

function customAdobeTracking(msg){
    try{
        if (addCTracking != null){
            addCTracking(msg);
        }
    }catch (error){
        console.error('addCTracking Error : ', error);
    }
}

window.addEventListener("aiseraButtonTracking", function () {
    aiseraBotLaunchButton = true;
    customAdobeTracking('AISERA BOT: LAUNCH BUTTON CLICKED');
    const el = document.querySelector('connect-ai-widget');
    el.setAttribute("openChatBot", true);
    // document.dispatchEvent(new CustomEvent('vaTriggerInit', { detail: { data: true } }));
});
//SM-6266 Adobe analytics tracking: END
function generateContextInfo() {
    const vaHistoryParsed = sessionStorage.getItem("VA_Details") ? JSON.parse(sessionStorage.getItem("VA_Details")) : null;
    const userEmail = sessionStorage.getItem("vaGuestEmail");
    const guestEmail = `guest-${Date.now() + (Math.random() * 100000).toFixed()}@vmware.com`;
    if(userDetails){
        let context = {};
        context.email = userDetails.email, // populate only when the user is logged in
        context.cn = userDetails.cn  // populate only when the user is logged in
        if (window.visitor && window.visitor.getMarketingCloudVisitorID()) {
            context.visitorid = window.visitor.getMarketingCloudVisitorID();
        }
        return context;
    } else if (((isArticleDetailPage && window.aisera_bot.page_title) || !isArticleDetailPage) && window.aisera_bot.visitorid != null) {
        //return { userEmail: `guest-${window.visitor.getMarketingCloudVisitorID()}@vmware.com`, visitorid: window.visitor.getMarketingCloudVisitorID() };
         return window.aisera_bot;

    } else if (window.visitor && window.visitor.getMarketingCloudVisitorID()) {
        return { userEmail: `guest-${window.visitor.getMarketingCloudVisitorID()}@vmware.com`, visitorid: window.visitor.getMarketingCloudVisitorID() };
    } else if (vaHistoryParsed && vaHistoryParsed["ab57fd0432e25d5b3013133a1c910d56"] && userEmail) {
        return { userEmail: guestEmail, visitorid: "" };
    } else {
        sessionStorage.setItem("vaGuestEmail", guestEmail);
        return { userEmail: guestEmail, visitorid: "" };
    }
}

(function () {
    const el = document.querySelector('connect-ai-widget');
     if(el) el.setAttribute("chatBotData", JSON.stringify(vaData));
    refreshAuthToken = true;
    vaAuthToken();
})();

function updateAiseraSession() {
    if (((isArticleDetailPage && window.aisera_bot.page_title) || !isArticleDetailPage) && window.aisera_bot.visitorid != null) {
        window.aisera_bot.url = window.location.href;
        //let message = {
        //type: 'aisera.update_session_vars'
        //};
        // window.postMessage(JSON.stringify(message), "*");
        window.vaData.contextInfo = generateContextInfo();
        const el = document.querySelector('connect-ai-widget');
        if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
        // document.dispatchEvent(new CustomEvent('updateVADetails', { detail: { data: true } }));
        
    }
}
window.addEventListener("logindetails", function (event) {
    if (event.detail.userType != "") {
        let context = {};
        userDetails = event.detail.userDetails;
        window.vaData.userInfo.email = userDetails.email;
        window.vaData.userInfo.name = userDetails.firstname + ' ' + userDetails.lastname;
        context.email = userDetails.email, // populate only when the user is logged in
        context.cn = userDetails.cn  // populate only when the user is logged in
        window.vaData.contextInfo = context;
        sessionStorage.setItem('vaGuestEmail', userDetails.email);
        //window.aisera_bot.userEmail = userDetails.email;
        //window.aisera_bot.accountId = userDetails.cn;
        //window.aisera_bot.userType = "Logged In User";
        //Need to dispatch event need to be called from here (Sunil will tell us the event details)
        //document.dispatchEvent(new CustomEvent('updateVADetails', { detail: { data: true } }));
    } else {
        userDetails = undefined;
    }
    const el = document.querySelector('connect-ai-widget');
    if(el) el.setAttribute("chatBotData", JSON.stringify(window.vaData));
});
function checkVisitorId() {
    //console.log("botcheckVisitorId");
    if (s == null || !("marketingCloudVisitorID" in s)) {
        setTimeout(checkVisitorId, 1500);
        return;
    } else {
        window.aisera_bot.visitorid = s.marketingCloudVisitorID;
        //console.log("botcheckVisitorId1",window.aisera_bot.visitorid);
        updateAiseraSession();
        //checkLumosLoad();
    }
}
window.addEventListener("articledetail", function (event) {
    try {
        let data = event.detail;
        let aiseraArticleInit = { page_title: data?.meta?.articleInfo?.title };
        if (aiseraArticleInit.page_title) {
            let title = aiseraArticleInit.page_title;
            aiseraArticleInit.documentid = title.substring(title.lastIndexOf("(") + 1, title.lastIndexOf(")"));
        }
        window.aisera_bot = Object.assign(window.aisera_bot, aiseraArticleInit);
        updateAiseraSession();
    } catch (e) { }
});
if (!isArticleDetailPage) {
    updateAiseraSession();
}
checkVisitorId();
