let url = new URL(location.href);
let isTransfer = window.sessionStorage.getItem("isTransfer");
let createCase = url.searchParams.get("createCase");
let contact = url.searchParams.get("firstName");
let numTransfers = +url.searchParams.get("numTransfers");
let previousWaitTime = +url.searchParams.get("previousWaitTime");
let authenticationCheckRunning = false;
let checkAuthStatusTimer;
let cookie = document.cookie.match(new RegExp("(^| )ctsignintray=([^;]+)"));
let isIframe = window.top !== window.self;
let chatButtonMinimized;
let cancelButtonSearchCount = 0;
let scriptElement = document.createElement("script");
let showWidget;
let prodEnvironments = [
    "business.ct.gov",
    "portal.ct.gov",
    "service.ct.gov",
    "service-chat.ct.gov",
];
let domainPath;
let sitePath;
let orgId;
let chatAgentEndpoint;
let chatContentEndpoint;
let deploymentId;
let buttonId;
let embeddedServiceDeployment;
let eswLiveAgentDevName;
let chatSessionActive = false;
let openConditionsCheckInterval = null;

const SITECORE_INIT_EVT = "Sitecore Session Initialization";

if (!isIframe) {
    setchasitorSessionData({
        contextUserId: "",
        contactId: "",
        origin: this.originationUrl,
        firstName: "",
        lastName: "",
        forgerockAuthenticated: cookie != null ? true : false,
        pendingAuthStatusChange: false,
        forgerockGUID: "",
    });
}

if (prodEnvironments.includes(location.hostname)) {
    domainPath = "https://ctds.my.salesforce.com";
    sitePath = "https://service-chat.ct.gov";
    orgId = "00Dt0000000PNLu";
    chatAgentEndpoint = "https://d.la1-c1-ttd.salesforceliveagent.com/chat";
    chatContentEndpoint =
        "https://c.la1-c1-ttd.salesforceliveagent.com/content";
    deploymentId = "572t0000000TNHn";
    buttonId = "573t0000000blOo";
    embeddedServiceDeployment = "Robin_2_1";
    eswLiveAgentDevName =
        "EmbeddedServiceLiveAgent_Parent04It0000000XZBAEA4_17fac59e75d";
}

scriptElement.setAttribute("src", domainPath + "/lightning/lightning.out.js");
scriptElement.setAttribute("onload", "loadLightningOut()");
document.body.appendChild(scriptElement);

window.addEventListener("DOMContentLoaded", init, false);
window.addEventListener("submitFeedback", submitFeedback);
window.addEventListener("showWidget", (e) => {
    showWidget = e.detail;
    renderWidget();
});

window.addEventListener("message", (e) => {
    //Store all important session data (sharable across tabs and across domains with postmessage)
    if (e.origin !== sitePath) {
        //Check if the message says anything about the context user auth status
        if (
            e.data.hasOwnProperty("pendingAuthStatusChange") &&
            e.data.pendingAuthStatusChange
        ) {
            //Retrieve chasitorSessionData from local storage
            setchasitorSessionData(e.data);

            if (!e.data.forgerockAuthenticated && chatSessionActive) {
                let chasitorSessionData = e.data;
                chasitorSessionData.firstName = "";
                chasitorSessionData.lastName = "";
                chasitorSessionData.forgerockAuthenticated = false;
                chasitorSessionData.contextUserId = "";
                chasitorSessionData.contactId = "";
                chasitorSessionData.ForgerockGUID = "";
                sendAuthMessage(getChasitorSessionData());
                if (chatSessionActive) {
                    removeChasitorSessionData();
                    endChat();

                    clearInterval(checkAuthStatusTimer);
                    authenticationCheckRunning = false;
                    chatSessionActive = false;
                    clearPrechatDetailsAndEndChat();
                }
            } else if (chatSessionActive) {
                sendAuthMessage(getChasitorSessionData());
            }
        }
        //Ignore all other instances of messages posted from the same sitepath.
        return;
    }

    let language;
    let url;
    if (isIframe) {
        let queryString = window.location.href;
        let urlParams = queryString.split("?")[1].split("&");
        language = urlParams[0].split("=")[1];
        url = urlParams[1].split("=")[1];
    } else {
        cookie = document.cookie.match(
            new RegExp("(^| )" + e.data.detail + "=([^;]+)")
        );
        language = cookie[2];
        url = location.hostname + location.pathname;
    }
    document.querySelector("iframe.snapins_postChat").contentWindow.postMessage(
        {
            detail: {
                language: language,
                url: url,
            },
        },
        "*"
    );
});
window.addEventListener("snippetNotification", processSnippetNotification);
window.onload = checkHelpButtonLoaded();

//Sets the store of data to local storage
function setchasitorSessionData(sessionData) {
    if (sessionData) {
        window.sessionStorage.setItem(
            "chasitorSessionData",
            JSON.stringify(sessionData)
        );
    }
}

//Gets the share of data from the local storage.
function getChasitorSessionData() {
    return JSON.parse(window.sessionStorage.getItem("chasitorSessionData"));
}

function removeChasitorSessionData() {
    window.sessionStorage.removeItem("chasitorSessionData");
}

//Initializes the chat session
function init() {
    chatSessionActive = true;
    //Retrieve chasitorSessionData from local storage
    let chasitorSessionData = getChasitorSessionData();

    //If no chasitorSessionData found in sessionStorage, Create the template
    if (!chasitorSessionData) {
        setchasitorSessionData({
            contextUserId: "",
            contactId: "",
            origin: this.originationUrl,
            firstName: "",
            lastName: "",
            forgerockAuthenticated: false,
            pendingAuthStatusChange: false,
            forgerockGUID: "",
            chatKey: "",
        });
    }

    //Needs comments...
    if (isTransfer) setDefaultMinimizedText("Please wait...");

    window.addEventListener("transfer", (e) => {
        let url;

        if (e.detail) {
            let metadata = e.detail.metadata;
            let transcript = e.detail.transcript;
            let transferOriginationName = e.detail.transferOriginationName;
            let transferUrl = e.detail.transferUrl;

            url =
                transferUrl +
                "?baseLiveAgentContentURL=" +
                encodeURIComponent(metadata.baseLiveAgentContentURL__c) +
                "&baseLiveAgentURL=" +
                encodeURIComponent(metadata.baseLiveAgentURL__c) +
                "&baseURL=" +
                encodeURIComponent(metadata.Base_URL__c) +
                "&deploymentAPIName=" +
                metadata.Deployment_API_Name__c +
                "&buttonId=" +
                metadata.buttonId__c +
                "&deploymentId=" +
                metadata.deploymentId__c +
                "&orgId=" +
                metadata.Org_ID__c +
                "&siteURL=" +
                encodeURIComponent(metadata.Site_URL__c) +
                "&eswLiveAgentDevName=" +
                metadata.eswLiveAgentDevName__c +
                "&createCase=" +
                metadata.Create_Case__c +
                "&transferOriginationName=" +
                (transferOriginationName ? transferOriginationName : "") +
                "&transferOriginationURL=" +
                encodeURIComponent(transcript.Origination__c) +
                "&priorChatDuration=" +
                transcript.ChatDuration;

            if (transcript.Contact) {
                url +=
                    "&firstName=" +
                    transcript.Contact.FirstName +
                    "&lastName=" +
                    transcript.Contact.LastName +
                    "&email=" +
                    encodeURIComponent(transcript.Contact.Email);
            }

            if (transcript.Transfers_to_Agent__c) {
                url += "&numTransfers=" + transcript.Transfers_to_Agent__c;
            }

            if (transcript.WaitTime) {
                url += "&previousWaitTime=" + transcript.WaitTime;
            }
        }

        // Clear the session variables
        window.sessionStorage.clear();
        window.sessionStorage.setItem("isTransfer", true);
        location.href = url;
    });

    window.addEventListener("endChat", (e) => {
        if (!chatSessionActive) {
            embedded_svc.liveAgentAPI.endChat();
            setDefaultMinimizedText("Please wait...").bind(this);
        }
    });

    window.addEventListener("getChatKey", sendChatKey);
    window.addEventListener(
        "beginCheckAuthentication",
        monitorAuthCheckWatchdog
    );
}

//Needs comments...
function submitFeedback(event) {
    const buttons = document.querySelectorAll(
        "button.embeddedServiceLiveAgentStateChatButtonItem"
    );
    const input = document.querySelector("textarea.chasitorText");
    for (let element of buttons) {
        event.detail === "start"
            ? element.setAttribute("disabled", true)
            : element.removeAttribute("disabled", false);
    }
    event.detail === "start"
        ? input.setAttribute("disabled", true)
        : input.removeAttribute("disabled");
}

//Needs comments
function checkHelpButtonLoaded() {
    let helpButton = document.querySelector(".helpButton");
    if (!helpButton) {
        window.setTimeout(checkHelpButtonLoaded, 500);
        return;
    } else {
        chatButtonMinimized =
            document.querySelector("div.embeddedServiceHelpButton").style
                .display === ""
                ? true
                : false;
        if (chatButtonMinimized && !isTransfer) window.sessionStorage.clear();
        if (isIframe) {
            let height = helpButton.clientHeight;
            let width = helpButton.clientWidth;
            window.parent.postMessage(
                {
                    frameHeight: height,
                    frameWidth: width,
                },
                "*"
            );
        }
    }
}

//Checks if the authentication check interval is running.  If not, it is started.
function monitorAuthCheckWatchdog() {
    if (!authenticationCheckRunning) {
        checkAuthStatusTimer = setInterval(checkAuthStatus, 1000);
        authenticationCheckRunning = true;
    }
}

//Checks the status of authentication and notifies the bot of any change if needed
function checkAuthStatus() {
    //If not iframed, the cookie is polled here as the parent does not exist.
    //If iframed, this script does not have access to the cookie, so auth events are driven by messages posed from the parent
    /*
  if(!isIframe){

    when we get forgerockId, we'll send that to the bot.  This block will be reduced and reimplemented.
    let newCookieState = document.cookie.match(new RegExp('(^| )ctsignintray=([^;]+)'));
    let chasitorSessionData = getChasitorSessionData();

    if(!cookie && newCookieState){

      chasitorSessionData.forgerockAuthenticated = true;
      chasitorSessionData.forgerockGUID = '';
      chasitorSessionData.contextUserId = '005r0000007bhtOAAQ';
      chasitorSessionData.contactId = '003r000000slGU3AAM';
      chasitorSessionData.firstName = 'Travis';
      chasitorSessionData.lastName = 'Cucore';
      setchasitorSessionData(chasitorSessionData);
      sendAuthMessage(chasitorSessionData);

    }else if(cookie && !newCookieState){

      chasitorSessionData.forgerockAuthenticated = false;
      chasitorSessionData.forgerockGUID = '';
      chasitorSessionData.firstName = '';
      chasitorSessionData.lastName = '';
      chasitorSessionData.contextUserId = '';
      chasitorSessionData.contactId = '';

      removeChasitorSessionData(chasitorSessionData);
      endChat();
      clearInterval(checkAuthStatusTimer);

      authenticationCheckRunning = false;
      chatSessionActive = false;

      clearPrechatDetailsAndEndChat();
    }
    cookie = newCookieState;

  }
  */
}

//Sends an auth message tothe bot via embedded service.  Presents as a hidden message and is processed by Apex
function sendAuthMessage(chasitorDetails) {
    let customerId = chasitorDetails.contextUserId
        ? chasitorDetails.contextUserId
        : "";
    let authStatus = chasitorDetails.forgerockAuthenticated
        ? "authenticated"
        : "unauthenticated";
    let action = chasitorDetails.forgerockAuthenticated ? "login" : "logout";
    let chatKey = chasitorDetails.chatKey;

    //Compose the auth message
    let message = {
        "[CUST-SIGNIN-STATUS]": {
            customerId: customerId,
            ActionType: action,
            AuthStatus: authStatus,
            Name: `${chasitorDetails.firstName} ${chasitorDetails.lastName}`,
            ActionId: Date.now(),
        },
        ChatKey: chatKey,
    };

    //Set the authenticated state based on message to be sent.  If logging in, set auth to true.  Then store in local storage
    chasitorDetails.pendingAuthStatusChange = false;
    setchasitorSessionData(chasitorDetails);

    //Post the auth message to the bot via embedded service.
    if (chatSessionActive) {
        embedded_svc.postMessage(
            "chasitor.sendMessage",
            JSON.stringify(message)
        );
    }
}

//Starts a new session.  Sets some pre-chat details.

function startNewSession() {
    if (isTransfer) {
        setTimeout(() => {
            options = {
                extraPrechatFormDetails: [
                    {
                        label: "Origination",
                        value: location.href,
                        displayToAgent: true,
                        transcriptFields: ["Origination__c"],
                    },
                    {
                        label: "Direct to Agent Transfer",
                        value: true,
                        displayToAgent: false,
                        transcriptFields: ["Direct_to_Agent_Transfer__c"],
                    },
                    {
                        label: "# Transfers to Agent",
                        ...(numTransfers
                            ? {
                                  value: numTransfers + 1,
                              }
                            : {
                                  value: 1,
                              }),
                        displayToAgent: true,
                        transcriptFields: ["Transfers_to_Agent__c"],
                    },
                    {
                        label: "Transfer Origination Name",
                        value: url.searchParams.get("transferOriginationName"),
                        displayToAgent: true,
                        transcriptFields: ["Transfer_Origination_Name__c"],
                    },
                    {
                        label: "Transfer Origination URL",
                        value: decodeURIComponent(
                            url.searchParams.get("transferOriginationURL")
                        ),
                        displayToAgent: true,
                        transcriptFields: ["Transfer_Origination_URL__c"],
                    },
                    {
                        label: "Prior Chat Duration",
                        value: url.searchParams.get("priorChatDuration"),
                        displayToAgent: true,
                        transcriptFields: ["Prior_Chat_Duration__c"],
                    },
                ],
            };
            if (contact) {
                options.extraPrechatInfo = [
                    {
                        entityName: "Contact",
                        showOnCreate: true,
                        saveToTranscript: "ContactId",
                        ...(createCase === "true"
                            ? {
                                  linkToEntityName: "Case",
                              }
                            : {}),
                        ...(createCase === "true"
                            ? {
                                  linkToEntityField: "ContactId",
                              }
                            : {}),
                        entityFieldMaps: [
                            {
                                doCreate: false,
                                doFind: true,
                                fieldName: "LastName",
                                isExactMatch: true,
                                label: "Last Name",
                            },
                            {
                                doCreate: false,
                                doFind: true,
                                fieldName: "FirstName",
                                isExactMatch: true,
                                label: "First Name",
                            },
                            {
                                doCreate: false,
                                doFind: true,
                                fieldName: "Email",
                                isExactMatch: true,
                                label: "Email",
                            },
                        ],
                    },
                ];
                options.extraPrechatFormDetails.push(
                    {
                        label: "First Name",
                        value: url.searchParams.get("firstName"),
                        displayToAgent: true,
                    },
                    {
                        label: "Last Name",
                        value: url.searchParams.get("lastName"),
                        displayToAgent: true,
                    },
                    {
                        label: "Email",
                        value: decodeURIComponent(
                            url.searchParams.get("email")
                        ),
                        displayToAgent: true,
                    }
                );
            }
            if (createCase === "true" && contact) {
                options.extraPrechatFormDetails.push(
                    {
                        label: "Case Email",
                        value: decodeURIComponent(
                            url.searchParams.get("email")
                        ),
                        displayToAgent: true,
                    },
                    {
                        label: "Case First Name",
                        value: decodeURIComponent(
                            url.searchParams.get("firstName")
                        ),
                        displayToAgent: true,
                    },
                    {
                        label: "Case Origin",
                        value: "Chat - Automatic",
                        displayToAgent: true,
                    }
                );
                options.extraPrechatInfo.push({
                    entityName: "Case",
                    showOnCreate: true,
                    saveToTranscript: "CaseId",
                    entityFieldMaps: [
                        {
                            isExactMatch: false,
                            fieldName: "SuppliedEmail",
                            doCreate: true,
                            doFind: false,
                            label: "Case Email",
                        },
                        {
                            isExactMatch: false,
                            fieldName: "SuppliedName",
                            doCreate: true,
                            doFind: false,
                            label: "Case First Name",
                        },
                        {
                            isExactMatch: false,
                            fieldName: "Origin",
                            doCreate: true,
                            doFind: false,
                            label: "Case Origin",
                        },
                    ],
                });
            }
            if (previousWaitTime) {
                options.extraPrechatFormDetails.push({
                    label: "Previous Wait Time",
                    value: previousWaitTime,
                    displayToAgent: true,
                    transcriptFields: ["Previous_Wait_Time__c"],
                });
            }

            embedded_svc.liveAgentAPI.startChat(options);
        }, 1000);
    }
}

function setDefaultMinimizedText(text) {
    let transferCSS = document.querySelector("#transfer-css");
    if (text && !transferCSS) {
        let style = document.createElement("style");
        style.id = "transfer-css";
        style.innerHTML = `
        div.helpButton span.message {
            background-color: blue;
            display: none;
        }
        div.helpButton span.helpButtonLabel::after {
            content: \'${text}\';
        }`;
        document.head.appendChild(style);
    } else if (transferCSS) document.head.removeChild(transferCSS);
}

function setOnclickEvents() {
    setTimeout(() => {
        let endChatButton = document.querySelector(
            "div.endChatContainer button.endChatButton"
        );
        let closeButton = document.querySelector("embeddedservice-chat-header")
            ? document
                  .querySelector("embeddedservice-chat-header")
                  .shadowRoot.querySelector("button.closeButton")
            : null;
        let leaveButton = document.querySelector(
            "button.embeddedServiceSidebarButton"
        );
        if (endChatButton) {
            endChatButton.onclick = function () {
                endChat();
            };
        }
        if (closeButton) {
            closeButton.onclick = function () {
                endChat();
            };
        }
        if (leaveButton) {
            leaveButton.onclick = function () {
                endChat();
            };
        }
    }, 500);
}

function endChat() {
    if (isIframe && isTransfer) location.reload();
    sessionStorage.clear();
    clearInterval(checkAuthStatusTimer);
    authenticationCheckRunning = false;

    setDefaultMinimizedText(null);
}

function lookForCancelButton() {
    let cancelButton = document.querySelector("button.waitingCancelChat");
    let closeButton = document.querySelector("embeddedservice-chat-header")
        ? document
              .querySelector("embeddedservice-chat-header")
              .shadowRoot.querySelector("button.closeButton")
        : null;
    if (cancelButton && closeButton) {
        cancelButton.onclick = function () {
            setOnclickEvents();
        };
        closeButton.onclick = function () {
            setOnclickEvents();
        };
    } else {
        cancelButtonSearchCount++;
        if (cancelButtonSearchCount < 12) {
            setTimeout(lookForCancelButton, 500);
        }
    }
}

function sendChatKey() {
    let chasitorSessionData = getChasitorSessionData();
    if (chasitorSessionData) {
        let chatKey = chasitorSessionData.chatKey;
        window.dispatchEvent(
            new CustomEvent("chatKey", {
                detail: chatKey,
            })
        );
    }
}

var initESW = function (gslbBaseURL) {
    let chasitorSessionData = getChasitorSessionData();
    cookie = document.cookie.match(new RegExp("(^| )ctsignintray=([^;]+)"));

    embedded_svc.settings.displayHelpButton = true; //Or false
    embedded_svc.settings.language = ""; //For example, enter 'en' or 'en-US'
    embedded_svc.settings.defaultMinimizedText = "Chat with us"; //(Defaults to Chat with an Expert)
    embedded_svc.settings.disabledMinimizedText = "Offline"; //(Defaults to Agent Offline)

    embedded_svc.settings.loadingText = "Getting things ready"; //(Defaults to Loading)
    if (isIframe) {
        embedded_svc.settings.widgetWidth = 360;
        embedded_svc.settings.widgetHeight = 498;
    }
    // embedded_svc.settings.storageDomain = 'salesforce-sites.com'; //(Sets the domain for your deployment so that visitors can navigate subdomains during a chat session)

    // Settings for Chat
    //embedded_svc.settings.directToButtonRouting = function(prechatFormData) {
    // Dynamically changes the button ID based on what the visitor enters in the pre-chat form.
    // Returns a valid button ID.
    //};
    //embedded_svc.settings.prepopulatedPrechatFields = {}; //Sets the auto-population of pre-chat form fields
    //embedded_svc.settings.fallbackRouting = []; //An array of button IDs, user IDs, or userId_buttonId
    //embedded_svc.settings.offlineSupportMinimizedText = '...'; //(Defaults to Contact Us)

    embedded_svc.settings.enabledFeatures = ["LiveAgent"];
    embedded_svc.settings.entryFeature = "LiveAgent";
    embedded_svc.settings.autoOpenPostChat = true;
    embedded_svc.settings.extraPrechatFormDetails = [
        {
            label: "Origination",
            ...(isIframe
                ? {
                      value: document.referrer,
                  }
                : {
                      value: location.href,
                  }),
            displayToAgent: false,
            transcriptFields: ["Origination__c"],
        },
    ];

    if (isIframe) {
        embedded_svc.settings.extraPrechatFormDetails.push({
            label: "Iframe Origination",
            value: location.href,
            displayToAgent: false,
            transcriptFields: ["Iframe_Origination__c"],
        });
    }
    //If a cookie or local storage data store exist, AND the user is authenticated, add prechat related to the context user.
    if (chasitorSessionData.forgerockAuthenticated) {
        embedded_svc.settings.extraPrechatFormDetails.push(
            {
                label: "Context User Id",
                value: chasitorSessionData.contactId,
                displayToAgent: false,
                transcriptFields: ["ContactId"],
            },
            {
                label: "Context User Id",
                value: chasitorSessionData.contextUserId,
                displayToAgent: false,
                transcriptFields: ["Context_User_Id__c"],
            },
            {
                label: "First Name",
                value: chasitorSessionData.firstName,
                displayToAgent: true,
            },
            {
                label: "Last Name",
                value: chasitorSessionData.lastName,
                displayToAgent: true,
            },
            {
                label: "User Authenticated",
                value: true,
                displayToAgent: true,
                transcriptFields: ["User_Authenticated__c"],
            }
        );
        embedded_svc.settings.extraPrechatInfo = [
            {
                entityName: "Contact",
                showOnCreate: true,
                saveToTranscript: "ContactId",
                entityFieldMaps: [
                    {
                        doCreate: false,
                        doFind: true,
                        fieldName: "LastName",
                        isExactMatch: true,
                        label: "Last Name",
                    },
                    {
                        doCreate: false,
                        doFind: true,
                        fieldName: "FirstName",
                        isExactMatch: true,
                        label: "First Name",
                    },
                ],
            },
        ];

        chasitorSessionData.forgerockAuthenticated = true;
    } else {
        chasitorSessionData.forgerockAuthenticated = false;
    }

    setchasitorSessionData(chasitorSessionData);
    embedded_svc.addEventHandler("onSettingsCallCompleted", startNewSession);
    embedded_svc.addEventHandler("onChatEndedByChasitor", setOnclickEvents);
    embedded_svc.addEventHandler("onChatEndedByAgent", setOnclickEvents);
    embedded_svc.addEventHandler("onIdleTimeoutOccurred", setOnclickEvents);
    embedded_svc.addEventHandler("afterMaximize", lookForCancelButton);
    embedded_svc.addEventHandler("onChatRequestSuccess", (e) => {
        embedded_svc.liveAgentAPI.addCustomEventListener(
            "transferCustomer",
            (e) => {
                window.dispatchEvent(
                    new CustomEvent("beginCustomerTransfer", {
                        detail: e,
                    })
                );
            }
        );

        //Adds the chatKey to the sessionStorage Dataset
        chasitorSessionData.chatKey = e.liveAgentSessionKey;
        window.sessionStorage.setItem("chatKey", e.liveAgentSessionKey);
        setchasitorSessionData(chasitorSessionData);

        let closeButton = document
            .querySelector("embeddedservice-chat-header")
            .shadowRoot.querySelector("button.closeButton");
        closeButton.onclick = function () {
            setOnclickEvents();
        };
    });
    embedded_svc.addEventHandler("onAgentMessage", (e) => {
        const chatHeader = document
            .querySelector("embeddedservice-chat-header")
            .shadowRoot.querySelector(
                "h2[embeddedService-chatHeader_chatHeader]"
            );
        if (chatHeader.innerText !== "Waiting to Chat") {
            return;
        } else {
            chatHeader.innerText = "Robin";
        }
    });
    embedded_svc.addEventHandler("afterDestroy", () => {
        window.sessionStorage.clear();

        //Removes chat session specific data some of which is related to auth status.
        window.sessionStorage.removeItem("chasitorSessionData");
    });

    if (isIframe) {
        embedded_svc.addEventHandler("afterMinimize", function () {
            var sidebar = document.querySelector(
                ".embeddedServiceSidebarMinimizedDefaultUI"
            );
            var height = sidebar.clientHeight;
            var width = sidebar.clientWidth;
            window.parent.postMessage(
                {
                    frameHeight: height,
                    frameWidth: width,
                },
                "*"
            );
        });

        embedded_svc.addEventHandler("afterMaximize", function () {
            window.parent.postMessage(
                {
                    frameHeight: embedded_svc.settings.widgetHeight,
                    frameWidth: embedded_svc.settings.widgetWidth,
                },
                "*"
            );
            document.querySelector(
                "div.modalContainer.sidebarMaximized.layout-docked.embeddedServiceSidebar > div"
            ).style.height = "100%";
        });

        embedded_svc.addEventHandler("afterDestroy", function () {
            var height = document.querySelector(".helpButton").clientHeight;
            var width = document.querySelector(".helpButton").clientWidth;
            window.parent.postMessage(
                {
                    frameHeight: height,
                    frameWidth: width,
                },
                "*"
            );
        });
    }

    if (isTransfer) {
        embedded_svc.init(
            decodeURIComponent(url.searchParams.get("baseURL")),
            decodeURIComponent(url.searchParams.get("siteURL")),
            gslbBaseURL,
            url.searchParams.get("orgId"),
            url.searchParams.get("deploymentAPIName"),
            {
                baseLiveAgentContentURL: decodeURIComponent(
                    url.searchParams.get("baseLiveAgentContentURL")
                ),
                deploymentId: url.searchParams.get("deploymentId"),
                buttonId: url.searchParams.get("buttonId"),
                baseLiveAgentURL: decodeURIComponent(
                    url.searchParams.get("baseLiveAgentURL")
                ),
                eswLiveAgentDevName: url.searchParams.get(
                    "eswLiveAgentDevName"
                ),
                isOfflineSupportEnabled: false,
            }
        );
    } else {
        embedded_svc.init(
            domainPath,
            sitePath + "/chat",
            gslbBaseURL,
            orgId,
            embeddedServiceDeployment,
            {
                baseLiveAgentContentURL: chatContentEndpoint,
                deploymentId: deploymentId,
                buttonId: buttonId,
                baseLiveAgentURL: chatAgentEndpoint,
                eswLiveAgentDevName: eswLiveAgentDevName,
                isOfflineSupportEnabled: false,
            }
        );
    }

    //Start interval timer that checks if the conditions are ready to open the bot every half-second.
    openConditionsCheckInterval = window.setInterval(() => {
        checkOpenChatConditions();
    }, 500);
};

//Checks if waits for the embeded_svc and the help button to laod,
//then checks if loadOnStart is presetn.  If so, a chat is opened.
function checkOpenChatConditions() {
    if (
        typeof embedded_svc != undefined &&
        document.querySelector(".helpButton") != null
    ) {
        //Clears the interval when the embedded_svc and help button are availible.
        window.clearInterval(openConditionsCheckInterval);

        //attempts top get loadOnStart from search parameters
        let loadOnStart = new URLSearchParams(window.location.search).get(
            "loadOnStart"
        );

        //if loadOnStart was 'true' then the chatbot is opened.
        if (loadOnStart === "true") {
            openChat();
        }
    }
}

//opens the chat window.
function openChat() {
    //Just in case someone uses this function somewhere else, check for dependencies and log something to help with debugging.
    if (
        embedded_svc == undefined ||
        document.querySelector(".helpButton") == undefined
    ) {
        console.log(
            "The chat did not open because either the embedded_svc is undefined, or the help button is not loaded yet."
        );
    } else {
        //open the chatbot.
        embedded_svc.liveAgentAPI.startChat(embedded_svc.liveAgentAPI.buttonId);
    }
}

function loadLightningOut() {
    let div = document.createElement("lightning-out-div");
    document.body.appendChild(div);
    $Lightning.use(
        "embeddedService:sidebarApp",
        function () {
            $Lightning.createComponent(
                "c:robinBotDisplayWidget",
                {
                    originationUrl: window.location.href,
                },
                div,
                function () {
                    console.log("robinBotDisplayWidget rendered");
                }
            );
        },
        sitePath + "/chat"
    );
}

function renderWidget() {
    if (showWidget == true) {
        if (!window.embedded_svc) {
            var s = document.createElement("script");
            s.setAttribute(
                "src",
                domainPath + "/embeddedservice/5.0/esw.min.js"
            );
            s.onload = function () {
                initESW(null);
            };
            document.body.appendChild(s);
        } else {
            initESW("https://service.force.com");
        }
    }
}

function processSnippetNotification(e) {
    let runSnippet =
        sessionStorage.getItem("hasWelcomeDialogRan") === null ? true : false;
    if (runSnippet) {
        let message;
        if (e.detail === SITECORE_INIT_EVT) {
            message = {
                "[REDIRECT-DIALOG-MSG]": {
                    dialogName: e.detail,
                },
            };
        }
        window.sessionStorage.setItem("hasWelcomeDialogRan", true);
        embedded_svc.postMessage(
            "chasitor.sendMessage",
            JSON.stringify(message)
        );
    }
}

function clearPrechatDetailsAndEndChat() {
    embedded_svc.settings.ChatKey = "";
    embedded_svc.liveAgentAPI.clearSession();
    embedded_svc.settings.extraPrechatFormDetails.forEach((element) => {
        if (
            element.label !== "Origination" &&
            element.label !== "IframeOrigination"
        ) {
            element.value = "";
        }
        return element;
    });
}