let cookie = document.cookie.match(new RegExp("(^| )chatBotCstId=([^;]+)"));
let userAuthenticated;
let esdConfig = {};
let pageType = "";
let clickedButtonBlinking = false;
let shiseidoDomains = [
  "development.shiseido.com",
  "staging.shiseido.com",
  "www.shiseido.com",
  "zh.development.shiseido.com",
  "zh.shiseido.com",
  "es.development.shiseido.com",
  "es.shiseido.com",
  "dev18-emea-shiseido.demandware.net",
];
let narsDomains = [
  "development.narscosmetics.com",
  "staging.narscosmetics.com",
  "www.narscosmetics.com",
];
let cpbDomains = [
  "development.cledepeaubeaute.com",
  "staging.cledepeaubeaute.com",
  "www.cledepeaubeaute.com",
];
let ddgDomains = [
  "development.drdennisgross.com",
  "staging.drdennisgross.com",
  "www.drdennisgross.com",
  "slalom-de-poc.s3.us-west-2.amazonaws.com"
];
let devEnvironmentDomain = [
  "development.shiseido.com",
  "development.narscosmetics.com",
  "development.cledepeaubeaute.com",
  "zh.development.shiseido.com",
  "es.development.shiseido.com",
  "development.drdennisgross.com",
];
let stagingEnvironmentDomain = [
  "staging.shiseido.com",
  "staging.narscosmetics.com",
  "staging.cledepeaubeaute.com",
  "dev18-emea-shiseido.demandware.net",
  "staging.drdennisgross.com"
];
let prodEnvironmentDomain = [
  "www.shiseido.com",
  "www.narscosmetics.com",
  "www.cledepeaubeaute.com",
  "zh.shiseido.com",
  "es.shiseido.com",
  "www.drdennisgross.com",
  "slalom-de-poc.s3.us-west-2.amazonaws.com"

];
let orgId;
let esdSiteHostURL;
let esdSecretUrl;
let esdEnvironmentUrl;
let resourceUrl;
let chatOrigin = window.location.hostname;
let chatUrl = window.location.href;
let enterpriseCode;
let brand;
let showStandardButton;
let isMobileSession = window.innerWidth <= 800 && window.innerHeight <= 600;
let siteLocation;
let chatInteraction;
let chatType;
let chatAvailable = false;
let needsStartGaEvent = true;
let hasFiredChatTransferredGAEvent = false;
let isAuthenticatedPreChat = false;
let hideChatButtonOnLoad = true;

const standardButtonLabel = "Chat with an Expert";
let theEnvironment = '';

function initializeENV() {
  //Initialize ESD vars for environment
  console.log('chatOrigin: ' + chatOrigin);
  console.log('chatUrl '  + chatUrl);

  if (devEnvironmentDomain.includes(chatOrigin)) {
    // SFCC
    console.log('CHATBOT: I AM IN DEVELOPMENT');
    theEnvironment = 'development';
    console.log('devEnvironmentDomain.includes(chatOrigin): ' +  devEnvironmentDomain.includes(chatOrigin));
    orgId = "00DWr000002luQb";
    esdSiteHostURL = "https://shiseido--ddgchatbot.sandbox.my.site.com/ESWMIAWESD1736544315841";
    esdSecretUrl = "https://shiseido--ddgchatbot.sandbox.my.salesforce-scrt.com";
    resourceUrl =  'https://shiseido--ddgchatbot.sandbox.my.salesforce-sites.com/resourceserver/resource';
  } else if (stagingEnvironmentDomain.includes(chatOrigin)) {
    // SFCC Staging
    console.log('CHATBOT: I AM IN STAGING');
    theEnvironment = 'staging';
    console.log('stagingEnvironmentDomain.includes(chatOrigin): ' +  devEnvironmentDomain.includes(chatOrigin));
    orgId = "00DWF000001TJ0H";
    esdSiteHostURL = "https://shiseido--full.sandbox.my.site.com/ESWDDGESDMIAW1741110744902";
    esdSecretUrl = "https://shiseido--full.sandbox.my.salesforce-scrt.com";
    resourceUrl =  'https://shiseido--full.sandbox.my.salesforce-sites.com/resourceserver/resource';
  } else if (prodEnvironmentDomain.includes(chatOrigin)) {
    // SFCC Prod
    console.log('CHATBOT: I AM IN PRODUCTION');
    theEnvironment = 'production';
    orgId = "00D3i000000EaZa";
    esdSiteHostURL =
      "https://shiseido.my.site.com/ESWShiseidoESDMIAW1749766072863";
    esdSecretUrl = "https://shiseido.my.salesforce-scrt.com";
    resourceUrl =  'https://shiseido.my.salesforce-sites.com/resourceserver/resource';
  }
  //Initialize ESD vars for brands
  if (shiseidoDomains.includes(chatOrigin) || shiseidoDomains.includes(chatUrl)) {
    enterpriseCode = "SHI-US";
    brand = "Shiseido";
    console.log('CHATBOT: I AM IN Shiseido');
    console.log('CHATBOT: theEnvironment: ' + theEnvironment);
    esdConfig.esdDevName = "Shiseido_ESD_MIAW";
    hideChatButtonOnLoad = true;
    //Import brand styles
    if(theEnvironment == 'production') {
      esdSiteHostURL =      "https://shiseido.my.site.com/ESWShiseidoESDMIAW1749766072863";
      esdSecretUrl = "https://shiseido.my.salesforce-scrt.com";
    } else if(theEnvironment == 'staging') {
      esdSiteHostURL = 'https://shiseido--full.sandbox.my.site.com/ESWShiseidoESDMIAW1741120298618';
      esdSecretUrl = 'https://shiseido--full.sandbox.my.salesforce-scrt.com';
    } else if(theEnvironment == 'development') {
        // old https://shiseido--ddgchatbot.sandbox.my.site.com/ESWDDGESDMIAW1737923477600
        // new https://shiseido--ddgchatbot.sandbox.my.site.com/ESWShiseidoESDMIAW1737922178880
      esdSiteHostURL = 'https://shiseido--ddgchatbot.sandbox.my.site.com/ESWShiseidoESDMIAW1737922178880';
      esdSecretUrl = 'https://shiseido--ddgchatbot.sandbox.my.salesforce-scrt.com';
    }
    document
      .getElementsByTagName("head")[0]
      .insertAdjacentHTML(
        "beforeend",
        '<link rel="stylesheet" href="' +
          resourceUrl +
          '/ShiseidoBotStyles_addtl" />'
      );
  }
  else if (narsDomains.includes(chatOrigin) || narsDomains.includes(chatUrl)) {
    enterpriseCode = "NARS-US";
    brand = "NARS";
    console.log('CHATBOT: I AM IN NARS');
    esdConfig.esdDevName = "NARS_ESD_MIAW";
    hideChatButtonOnLoad = true;
    //Import brand styles
    if(theEnvironment == 'production') {
      esdSiteHostURL =      "https://shiseido.my.site.com/ESWNARSESDMIAW1749765879434";
      esdSecretUrl = "https://shiseido.my.salesforce-scrt.com";
    } else if(theEnvironment == 'staging') {
      esdSiteHostURL = 'https://shiseido--full.sandbox.my.site.com/ESWNARSESDMIAW1741125822955';
      esdSecretUrl = 'https://shiseido--full.sandbox.my.salesforce-scrt.com';
    } else if(theEnvironment == 'development') {
      esdSiteHostURL = 'https://shiseido--ddgchatbot.sandbox.my.site.com/ESWNARSESDMIAW1737923589738';
      esdSecretUrl = 'https://shiseido--ddgchatbot.sandbox.my.salesforce-scrt.com';
    }

    document
      .getElementsByTagName("head")[0]
      .insertAdjacentHTML(
        "beforeend",
        '<link rel="stylesheet" href="' +
          resourceUrl +
          '/NARSBotStyles" />'
      );
  } else if (cpbDomains.includes(chatOrigin) || cpbDomains.includes(chatUrl)) {
    enterpriseCode = "CPB-US";
    brand = "CPB";
    esdConfig.esdDevName = "CPB_ESD_MIAW";
    console.log('CHATBOT: I AM IN CPB');
    hideChatButtonOnLoad = false;
    if(theEnvironment == 'production') {
      esdSiteHostURL =      "https://shiseido.my.site.com/ESWCPBESDMIAW1749765503505";
      esdSecretUrl = "https://shiseido.my.salesforce-scrt.com";
    } else if(theEnvironment == 'staging') {
      esdSiteHostURL = 'https://shiseido--full.sandbox.my.site.com/ESWCPBESDMIAW1741105684441';
      esdSecretUrl = 'https://shiseido--full.sandbox.my.salesforce-scrt.com';
    } else if(theEnvironment == 'development') {
      esdSiteHostURL = 'https://shiseido--ddgchatbot.sandbox.my.site.com/ESWCPBESDMIAW1737923392151';
      esdSecretUrl = 'https://shiseido--ddgchatbot.sandbox.my.salesforce-scrt.com';
    }

    //Import brand styles
    document
      .getElementsByTagName("head")[0]
      .insertAdjacentHTML(
        "beforeend",
        '<link rel="stylesheet" href="' +
          resourceUrl +
          '/CPBBotStyles" />'
      );
  } else if (ddgDomains.includes(chatOrigin) || ddgDomains.includes(chatUrl)) {
    enterpriseCode = "DDG-US";
    brand = "DDG";
    console.log('CHATBOT: I AM IN DDG');
    esdConfig.esdDevName = "DDG_ESD_MIAW";
    hideChatButtonOnLoad = false;
    if(theEnvironment == 'production') {
      esdSiteHostURL =      'https://shiseido.my.site.com/ESWDDGESDMIAW1749765720133';
      esdSecretUrl = "https://shiseido.my.salesforce-scrt.com";
    } else if(theEnvironment == 'staging') {
      esdSiteHostURL = 'https://shiseido--full.sandbox.my.site.com/ESWDDGESDMIAW1741110744902';
      esdSecretUrl = 'https://shiseido--full.sandbox.my.salesforce-scrt.com';
    } else if(theEnvironment == 'development') {
      esdSiteHostURL = 'https://shiseido--ddgchatbot.sandbox.my.site.com/ESWDDGESDMIAW1737923477600';
      esdSecretUrl = 'https://shiseido--ddgchatbot.sandbox.my.salesforce-scrt.com';
    }
    //Import brand styles
    document
      .getElementsByTagName("head")[0]
      .insertAdjacentHTML(
        "beforeend",
        '<link rel="stylesheet" href="' +
          resourceUrl +
          '/DDGBotStyles" />'
      );
  }

  if (!cookie) window.localStorage.removeItem("userAuthenticated");

    window.addEventListener("beginCheckAuthentication", checkAuthentication);
    if (!window.embeddedservice_bootstrap) {
      constructPrechatDetails();
      var s = document.createElement("script");
      s.setAttribute("src", esdSiteHostURL + "/assets/js/bootstrap.min.js");
      console.log(s.getAttribute("src"));
        console.log(document);
        console.log(document.body);
        console.log('Preparing to make onload call');
      s.setAttribute('src', esdSiteHostURL + '/assets/js/bootstrap.min.js');
      s.onload = function() {
        initEmbeddedMessaging();
      };
      console.log('building ESD');
      document.body.appendChild(s);
    }
}



async function getUserIp() {
  try {
    const response = await fetch("https://api.ipify.org?format=json", {
      method: "GET",
    });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    const userIp = data.ip;
    console.log("User IP Address:", userIp);
    ipAddress = userIp;
    return userIp;
  } catch (error) {
    console.error("Error fetching IP address:", error);
  }
}

async function initEmbeddedMessaging() {
  try {
    console.log("Entered initEmbeddedMessaging");
    ipAddress = await getUserIp(); // Get user IP asynchronously
    let mostRecentlyViewedPage = window.location.href;
    window.addEventListener("onEmbeddedMessagingReady", () => {
      console.log("Received the onEmbeddedMessagingReady event…");
      // Send data to Salesforce
      console.log("initEmbeddedMessaging - setting preChat fields");
      let prechatEmail = checkCookiePrechat();
      console.log('Prechat email: ' + prechatEmail);
      embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
        "enterpriseCode" : enterpriseCode,
				"brand" : brand,
				"IpAddress": ipAddress,
        "clickedButtonBlinking" : clickedButtonBlinking,
        "pageType" : pageType,
        "prechatEmail" : prechatEmail,
        "mostRecentlyViewedPage" : mostRecentlyViewedPage
        });
    });
    embeddedservice_bootstrap.settings.hideChatButtonOnLoad = hideChatButtonOnLoad;
    embeddedservice_bootstrap.settings.defaultMinimizedText = standardButtonLabel;
    embeddedservice_bootstrap.settings.displayHelpButton = false;
    embeddedservice_bootstrap.settings.language = "en_US"; // For example, enter 'en' or 'en-US'
    embeddedservice_bootstrap.settings.autoOpenPostChat = false;
    embeddedservice_bootstrap.settings.externalScripts = [
      "CustomEvents_fileTransferCustToAgent",
    ];

    embeddedservice_bootstrap.settings.displayHelpButton = false;

    console.log('esdSiteHostURL ' + esdSiteHostURL);

    console.log('esdConfig.esdDevName ' + esdConfig.esdDevName);

    console.log('esdSecretUrl ' + esdSecretUrl);

    console.log("initEmbeddedMessaging calling embeddedservice_bootstrap.init");
    embeddedservice_bootstrap.init(
      orgId,
      esdConfig.esdDevName,
      esdSiteHostURL,
      {
        scrt2URL: esdSecretUrl,
      }
    );



    window.addEventListener(
      "onEmbeddedMessagingConversationClosed",
      function (data) {
        console.log(
          "onSettingsCallCompleted event was fired. Agent availability status is " +
            data.isAgentAvailable
            ? "Chat online"
            : "Chat offline"
        );
        chatAvailable = data.isAgentAvailable;
        bindEventsToLinks();
        // if (!embedded_svc.settings.displayHelpButton && data.isAgentAvailable) {
        //   // createChatButton(esdConfig.desktopIconSrc, esdConfig.mobileIconSrc);
        //   showStorefrontCtas();
        // }
      }
    );

    if (pageType == "Cart" || pageType == "Checkout" || pageType == "product") {
      window.addEventListener("onEmbeddedMessagingButtonCreated", (event) => {
        console.log("Received the onEmbeddedMessagingButtonCreated event…");
        console.log("Event detail: ", event.detail);
        startPageTypeTimer();
      });
    }

    window.addEventListener(
      "botContext",
      function (evt) {
        let chatType = "Chat with ";
        chatInteraction = "Chat Transferred";
        if (evt.detail === "Customer Care") {
          chatType = chatType + "Customer Serivce";
        } else {
          chatType = chatType + evt.detail;
        }
        if (!hasFiredChatTransferredGAEvent) {
          hasFiredChatTransferredGAEvent = true;
          gaEventCapture(siteLocation, chatInteraction, chatType);
        }
      },
      false
    );


    //used to stop blinking after chat starts
    window.addEventListener("onEmbeddedMessagingReady", () => {
      console.log("Received the onEmbeddedMessagingReady event.");
      let button = document.querySelectorAll(
        ".embeddedMessagingConversationButton"
      );
      for (let i = 0; i < button.length; i++) {
        button[i].classList.remove("blinking");
      }
    });
    //end of blinking solution

    //Rebuild chat button after ESD destroyed
    window.addEventListener(
      "onEmbeddedMessagingConversationClosed",
      reinitializeChat
    );
    function reinitializeChat() {
      showStorefrontCtas();
      needsStartGaEvent = true;
    }
    //End rebuild ESD

    //Register listeners for GA Event Capture
    window.addEventListener("onEmbeddedMessagingReady", function (data) {
      gaEventCapture(siteLocation, "Chat Initiated");
      needsStartGaEvent = true;
    });

    //window.addEventListener("onQueueUpdate", function(data) {
    window.addEventListener(
      "onEmbeddedMessagingConversationRouted",
      function (data) {
        if (data.queuePosition == 0) {
          gaEventCapture(siteLocation, "Chat Accepted");
        }
      }
    );
    //End listeners for GA Event Capture
    //embeddedservice_bootstrap.settings.enabledFeatures = ['LiveAgent'];
    //embeddedservice_bootstrap.settings.entryFeature = 'LiveAgent';
  } catch (err) {
    console.error("Error loading Embedded Messaging: ", err);
  }
}

function constructPrechatDetails() {
      console.log("onloadFunction constructPrechatDetails initiated");

      // let pageType = window["pageContext"] ? window["pageContext"].type : '';
      pageType = '';

      //window["pageContext"] ? window["pageContext"].type : '';

      if (window.pageType != null && window.pageType != undefined) {
        pageType = window.pageType;
      } else if (
        window["pageContext"] != null &&
        window["pageContext"] != undefined &&
        window["pageContext"].type != null &&
        window["pageContext"].type != undefined
      ) {
        pageType = window["pageContext"].type;
      } else {
        pageType = "";
      }

      if (window["pageContext"]) {
        console.log("PageTitle ===> ", window["pageContext"].title);
        console.log("PageType ===> ", window["pageContext"].type);
        if (pageType == "Cart") {
          // || pageType == "SinglePageCheckout"
          startPageTypeTimer();
        }
      }
    }

    function startPageTypeTimer() {
      console.log("start page timer for cart awareness");
      let msToWait = 5;
      let msToBlink = 30;
      setTimeout(function () {
        let button = document.querySelectorAll(
          ".embeddedMessagingConversationButton"
        );

        for (let i = 0; i < button.length; i++) {
          button[i].classList.add("blinking");
        }
        clickedButtonBlinking = true;
        // embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
        //   clickedButtonBlinking: true,
        //   pageType: window["pageContext"].title,
        //   brand: brand,
        //   enterpriseCode: enterpriseCode,
        // });

        setTimeout(function () {
          for (let i = 0; i < button.length; i++) {
            button[i].classList.remove("blinking");
          }
        }, msToBlink * 1000);
      }, msToWait * 1000);
    }

/*********************************************************************************************************/
window.addEventListener("DirectStartChat", skipPrechat);
window.addEventListener(
  "chatConsentSelection",
  gaEventCaptureTranscriptConsent
);

function skipPrechat() {
  embeddedservice_bootstrap.utilAPI.launchChat();
  // need to do something else? CPK
}

function gaEventCaptureTranscriptConsent(consentSelection) {
  gaEventCapture("", consentSelection.detail.message, "");

  if (consentSelection.detail.message === "Consent Disagree") {
    embeddedservice_bootstrap.userVerificationAPI.clearSession(true);
  }
}

//Google Analytics event capture
function gaEventCapture(siteLocation, chatInteraction, chatType) {
	window.dataLayer.push({
		"event": "contactRequest",
		"contactType": "Messaging",
		"siteLocation": siteLocation,
		"chatInteraction": chatInteraction,
		"chatType": chatType,
		"pageCategory":  window.dataLayer[0].pageCategory,
		"pageSubCategory":  window.dataLayer[0].pageSubCategory
	});
}

function showStorefrontCtas() {
  const chatButtons = document.querySelectorAll(
    ".sfsc-chat-cta-artist, .sfsc-chat-cta-agent, .sfsc-chat-cta, .chatBot-side-banner"
  );
  for (let i = 0; i < chatButtons.length; i++) {
    // chatButtons[i].style.display = 'flex';
  }
}

function hideStorefrontCtas() {
  const chatButtons = document.querySelectorAll(
    ".sfsc-chat-cta-artist, .sfsc-chat-cta-agent, .sfsc-chat-cta, .chatBot-side-banner"
  );
  for (let i = 0; i < chatButtons.length; i++) {
    // chatButtons[i].style.display = 'none';
  }
}
if (!chatAvailable) {
  hideStorefrontCtas();
}

function bindStandardCTASToChatbot() {
  let btns = document.querySelectorAll(
    ".sfsc-chat-cta-artist, .sfsc-chat-cta-agent, .sfsc-chat-cta, .chatBot-side-banner, .livechat-sfsc-order, .livechat-sfsc-chatWithProductExpert"
  );

  for (let i = 0; i < btns.length; i++) {
    console.log("gl classname: " + btns[i].className);
    btns[i].addEventListener("click", function (e) {
      if (needsStartGaEvent) {
        needsStartGaEvent = false;
        initializeChat(
          isMobileSession ? "Flyout - Mobile" : "Flyout - Desktop",
          btns[i].className
        );
      }
    });
  }
}
function bindEventsToLinks() {
  //Creates "start chat" listeners for shared classes
  bindStandardCTASToChatbot();

  //Brand specific "start chat" listeners
  if (brand === "NARS") {
    //Binds "start chat" listeners when "Live Chat" footer clicked on NARS storefront
    const narsChatButton = document.querySelectorAll(".live-chat");
    for (let i = 0; i < narsChatButton.length; i++) {
      narsChatButton[i].addEventListener("click", function (e) {
        bindStandardCTASToChatbot();
      });
    }
  }

  if (window.location.href.indexOf("checkout") > -1) {
    const parentContainer = document.getElementsByClassName(
      "checkout-progress-container"
    );

    for (let i = 0; i < parentContainer.length; i++) {
      parentContainer[i].addEventListener(
        "DOMNodeInserted",
        nodeInserted,
        false
      );
    }
  }
}

function nodeInserted(b) {
  if (b.relatedNode.parentNode.classList.contains("step-3")) {
    bindStandardCTASToChatbot();
  }
}

function bindStandardCTASToChatbot() {
  let btns = document.querySelectorAll(
    ".sfsc-chat-cta-artist, .sfsc-chat-cta-agent, .sfsc-chat-cta, .chatBot-side-banner, .livechat-sfsc-order, .livechat-sfsc-chatWithProductExpert"
  );

  for (let i = 0; i < btns.length; i++) {
    console.log("gl classname: " + btns[i].className);
    btns[i].addEventListener("click", function (e) {
      if (needsStartGaEvent) {
        needsStartGaEvent = false;
        initializeChat(
          isMobileSession ? "Flyout - Mobile" : "Flyout - Desktop",
          btns[i].className
        );
      }
    });
  }
}

function checkCookiePrechat() {
  let toReturn = "";
  cookie = document.cookie.match(new RegExp("(^| )chatBotCstId=([^;]+)"));
  if (cookie) {
    console.log("found cookie!");
    toReturn = cookie[2];
    isAuthenticatedPreChat = true;
  }

  return toReturn;
}

function checkCookie() {
  cookie = document.cookie.match(new RegExp("(^| )chatBotCstId=([^;]+)"));
  userAuthenticated = window.localStorage.getItem("userAuthenticated");
  if (cookie && (userAuthenticated === "false" || !userAuthenticated)) {
    sendAuthMessage(cookie[2], "login");
  } else if (!cookie && userAuthenticated === "true") {
    sendAuthMessage(null, "logout");
  }
}

function sendAuthMessage(cookie, authStatus) {
  let message = {
    "[CUST-AUTH-MSG]": {
      authCookie: cookie,
    },
  };
  window.localStorage.setItem(
    "userAuthenticated",
    authStatus === "login" ? true : false
  );
  // if (!isAuthenticatedPreChat || cookie === null) {
  //   embedded_svc.postMessage("chasitor.sendMessage", JSON.stringify(message));
  // }
}

bindEventsToLinks();
//End initialize environment vars

//Guest identification actions
window.addEventListener("DOMContentLoaded", init);
function init() {
    console.log("init initiated - calling initializeENV()");
    initializeENV();
    console.log("init initiated - done calling initializeENV()");
}
function checkAuthentication() {
  cookieCheck = setInterval(checkCookie, 1000);
}

//Called by the custom button to start a chat and hide the button
function initializeChat(buttonSiteLocation, ctaClassName) {
  console.log("gl ctaClassName: " + ctaClassName);
  siteLocation = buttonSiteLocation;
  //Check for cookie pre-chat
  if (embeddedservice_bootstrap &&
      embeddedservice_bootstrap.prechatAPI &&
      embeddedservice_bootstrap.prechatAPI.HiddenPrechatFields !== undefined
  ) {
    embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
      prechatEmail: checkCookiePrechat(),
    });
  }
  if (ctaClassName === "concierge-help-cta livechat-sfsc-order") {
    console.log("gl question about order");
    embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
      pageType: "Shiseido_Order",
    });
    launchChat(ctaClassName);
  }
  else if (
    ctaClassName === "concierge-help-cta livechat-sfsc-chatWithProductExpert"
  ) {
    console.log("gl chat with product expert");
    embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
      pageType: "Shiseido_ExpertChat",
    });
    launchChat(ctaClassName);
  }


  //document.querySelector(".helpButtonEnabled").click();
  //hideStorefrontCtas();
}

let launchChat = (fromWhere) =>{
    console.log("starting chat from " + fromWhere);

    embeddedservice_bootstrap.utilAPI.showChatButton();
    embeddedservice_bootstrap.utilAPI.launchChat().then(() => {
        // Success handler used to perform actions
        // when the chat client launches successfully.
        // For example, create a method that disables the launch chat button.
        //disableLaunchChatButton();
        console.log('successfully launched chat');
    }).catch((e) => {
        // Error handler used to perform actions
        // if the chat client fails to launch.
        // For example, create a method that hides the launch chat button.
        //hideLaunchChatButton();
        console.log('launchChat error occurred ' + JSON.stringify(e));
        //try again due to timing of loading
        if(fromWhere == 'customerservice'){
            launchChat(fromWhere);
        }
    }).finally(() => {
        // Finally handler used to perform any clean-up actions
        // regardless of whether the chat client launches successfully or not.
        // For example, create a method that logs the user’s attempt to chat.
        //logEndUserAttemptToChat();

    });
    if(fromWhere != 'customerservice'){
        gaEventCapture(siteLocation, "Chat Button Clicked");
    }
};