let cookie = document.cookie.match(new RegExp('(^| )chatBotCstId=([^;]+)'));
let userAuthenticated;
let esdConfig = {};
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 devEnvironmentDomain = ['slalom-de-poc.s3.us-west-2.amazonaws.com', 'development.shiseido.com', 'development.narscosmetics.com', 'development.cledepeaubeaute.com', 'zh.development.shiseido.com', 'es.development.shiseido.com'];
let stagingEnvironmentDomain = ['staging.shiseido.com', 'staging.narscosmetics.com', 'staging.cledepeaubeaute.com', 'dev18-emea-shiseido.demandware.net'];
let prodEnvironmentDomain = ['www.shiseido.com', 'www.narscosmetics.com', 'www.cledepeaubeaute.com','zh.shiseido.com', 'es.shiseido.com'];
let orgId;
let esdSiteHostURL;
let esdEnvironmentUrl;
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;

const standardButtonLabel = 'Chat with an Expert';
const SHI_BOT_NAME = 'Virtual Assistant';
const NARS_BOT_NAME = 'Virtual Assistant';
const CPB_BOT_NAME = 'Virtual Assistant';

window.addEventListener('DirectStartChat', skipPrechat);
window.addEventListener('chatConsentSelection', gaEventCaptureTranscriptConsent);

function skipPrechat(){
	embedded_svc.liveAgentAPI.startChat();
}

//Initialize ESD vars for environment
if (devEnvironmentDomain.includes(chatOrigin)) { // SFCC Dev
	orgId = '00D8K0000008gdd';
	esdSiteHostURL = 'https://shiseido--chatbot2.sandbox.my.salesforce-sites.com/chatbot';
	esdEnvironmentUrl = 'https://shiseido--chatbot2.sandbox.my.salesforce.com';
	esdConfig.deploymentId = '5723i000000geYI';
	esdConfig.buttonId = '5733i000000cEl6';
	esdConfig.baseLiveAgentContentURL = 'https://c.la12s-core2.sfdc-lywfpd.salesforceliveagent.com/content';
	esdConfig.baseLiveAgentURL = 'https://d.la12s-core2.sfdc-lywfpd.salesforceliveagent.com/chat';
} else if (stagingEnvironmentDomain.includes(chatOrigin)) { // SFCC Staging
	orgId = '00DWF000001TJ0H';
	esdSiteHostURL = 'https://shiseido--full.sandbox.my.salesforce-sites.com/chatbot';
	esdEnvironmentUrl = 'https://shiseido--full.sandbox.my.salesforce.com';
	esdConfig.deploymentId = '5723i000000geYI';
	esdConfig.buttonId = '5733i000000cEl6';
	esdConfig.baseLiveAgentContentURL = 'https://c.la12s-core1.sfdc-8tgtt5.salesforceliveagent.com/content';
	esdConfig.baseLiveAgentURL = 'https://d.la12s-core1.sfdc-8tgtt5.salesforceliveagent.com/chat';
} else if (prodEnvironmentDomain.includes(chatOrigin)) { // SFCC Prod
	orgId = '00D3i000000EaZa';
	//esdSiteHostURL = 'https://buxomchat.secure.force.com/chatbot';
	esdSiteHostURL = 'https://shiseido.my.salesforce-sites.com/chatbot';
	esdEnvironmentUrl = 'https://shiseido.my.salesforce.com';
	esdConfig.deploymentId = '5723i000000geYI';
	esdConfig.buttonId = '5733i000000cEl6';
	//esdConfig.baseLiveAgentContentURL = 'https://c.la4-c2-ph2.salesforceliveagent.com/content';
	esdConfig.baseLiveAgentContentURL = 'https://c.la1-core1.sfdc-8tgtt5.salesforceliveagent.com/content';
	//esdConfig.baseLiveAgentURL = 'https://d.la4-c2-ph2.salesforceliveagent.com/chat';
	esdConfig.baseLiveAgentURL = 'https://d.la1-core1.sfdc-8tgtt5.salesforceliveagent.com/chat';
}

//Initialize ESD vars for brands
if (shiseidoDomains.includes(chatOrigin) || shiseidoDomains.includes(chatUrl)) {
	embedded_svc.settings.defaultMinimizedText = standardButtonLabel;
	embedded_svc.settings.displayHelpButton = false;
	enterpriseCode = 'SHI-US';
	brand = 'Shiseido';
	esdConfig.esdDevName = 'Shiseido_ESD';
	esdConfig.eswLiveAgentDevName = 'EmbeddedServiceLiveAgent_Parent04I3i000000bva7EAA_1823cc85ef9';
	esdConfig.chatbotAvatar = 'https://shiseido.ipscdn.net/sa1/on/demandware.static/-/Sites-shiseido_us-Library/default/dw0adc8875/sfsc/Shiseido.Camellia.Positive.RGB_d6001c.png';
	esdConfig.headerLogo = 'https://shiseido.ipscdn.net/sa1/on/demandware.static/-/Sites-shiseido_us-Library/default/dw0adc8875/sfsc/Shiseido.Logotype.Negative.2020.png';
	//Import brand styles
	document.getElementsByTagName("head")[0].insertAdjacentHTML(
		"beforeend",
		"<link rel=\"stylesheet\" href=\"" + esdSiteHostURL + "/resource/ShiseidoBotStyles_addtl\" />");

} else if (narsDomains.includes(chatOrigin) || narsDomains.includes(chatUrl)) {
	embedded_svc.settings.defaultMinimizedText = 'Chat with NARS';
	embedded_svc.settings.displayHelpButton = false;
	enterpriseCode = 'NARS-US';
	brand = 'NARS';
	esdConfig.esdDevName = 'NARS_ESD';
	esdConfig.eswLiveAgentDevName = 'EmbeddedServiceLiveAgent_Parent04I040000008OOXEA2_181e4b8032e';
	esdConfig.chatbotAvatar = 'https://www.narscosmetics.com/on/demandware.static/Sites-nars_us-Site/-/default/dw418d8902/images/nars-logo-black.png';
	esdConfig.headerLogo = 'https://www.narscosmetics.com/on/demandware.static/Sites-nars_us-Site/-/default/dw418d8902/images/nars-logo-white.png';
	//Import brand styles
	document.getElementsByTagName("head")[0].insertAdjacentHTML(
		"beforeend",
		"<link rel=\"stylesheet\" href=\"" + esdSiteHostURL + "/resource/NARSBotStyles\" />");

} else if (cpbDomains.includes(chatOrigin) || cpbDomains.includes(chatUrl)) {
	embedded_svc.settings.defaultMinimizedText = standardButtonLabel;
	embedded_svc.settings.displayHelpButton = false;
	enterpriseCode = 'CPB-US'
	brand = 'Cle de Peau Beaute';
	esdConfig.esdDevName = 'CPB_ESD';
	esdConfig.eswLiveAgentDevName = 'EmbeddedServiceLiveAgent_Parent04I040000008OOSEA2_181e4b4f204';
	esdConfig.chatbotAvatar = 'https://www.cledepeaubeaute.com/on/demandware.static/-/Sites-CPB-Library/default/dwcf39e2f6/sfsc/CPB_VirtualAssitant_Logo_Icon_40x40.png';
	esdConfig.headerLogo = 'https://www.cledepeaubeaute.com/on/demandware.static/-/Sites-CPB-Library/default/dwcf39e2f6/sfsc/CPB_Banner2.png';
	//Import brand styles
	document.getElementsByTagName("head")[0].insertAdjacentHTML(
		"beforeend",
		"<link rel=\"stylesheet\" href=\"" + esdSiteHostURL + "/resource/CPBBotStyles\" />");
}

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 setAssistantLabels(){
	let headerContainer = document.getElementsByTagName('embeddedservice-chat-header')[0];
	// headerContainer.getElementsByTagName('h2')[0].firstChild.data = 'Test';
	if(headerContainer.getElementsByTagName('h2')[0].firstChild.data === 'Virtual Assistant' || headerContainer.getElementsByTagName('h2')[0].firstChild.data === 'Connecting'){
		if(brand === 'Shiseido'){
			headerContainer.getElementsByTagName('h2')[0].firstChild.data = SHI_BOT_NAME;
		}else if(brand === 'Cle de Peau Beaute'){
			headerContainer.getElementsByTagName('h2')[0].firstChild.data = CPB_BOT_NAME;
		}else if(brand === 'NARS'){
			headerContainer.getElementsByTagName('h2')[0].firstChild.data = NARS_BOT_NAME;
		}
	}

	let agentNameContainer = document.getElementsByClassName('agentName');
	for (let i = 0; i < agentNameContainer.length; i++) {
		if(brand === 'Shiseido'){
			agentNameContainer[i].innerText = SHI_BOT_NAME;
		}else if(brand === 'Cle de Peau Beaute'){
			agentNameContainer[i].innerText  = CPB_BOT_NAME;
		}else if(brand === 'NARS'){
			agentNameContainer[i].innerText = NARS_BOT_NAME;
		}
		
	}

}

bindEventsToLinks();
//End initialize environment vars

//Guest identification actions
window.addEventListener('DOMContentLoaded', init);
function init() {
	console.log('init initiated');
	if (!cookie) window.localStorage.removeItem('userAuthenticated');

	window.addEventListener('beginCheckAuthentication', checkAuthentication);
}
function checkAuthentication() {
	cookieCheck = setInterval(checkCookie, 1000);
}
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 checkCookiePrechat() {
	let toReturn = '';
	cookie = document.cookie.match(new RegExp('(^| )chatBotCstId=([^;]+)'));
	if (cookie) {
		console.log('found cookie!');
		toReturn = cookie[2];
		isAuthenticatedPreChat = true;
	}

	return toReturn;
}
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));
	}
}
//End guest identification actions

//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(typeof embedded_svc.settings.extraPrechatFormDetails != "undefined"){
		embedded_svc.settings.extraPrechatFormDetails.push({  
			"value": checkCookiePrechat(),
			"transcriptFields":[ "Prechat_Email__c" ]
		});
	}
	if(ctaClassName === 'concierge-help-cta livechat-sfsc-order' ){
		console.log('gl question about order');
		embedded_svc.settings.extraPrechatFormDetails.push({  
			"value": "Shiseido_Order",
			"transcriptFields":[ "Page_Type__c" ]
		});
	}
	if (ctaClassName === 'concierge-help-cta livechat-sfsc-chatWithProductExpert') {
		console.log('gl chat with product expert');
		embedded_svc.settings.extraPrechatFormDetails.push({  
			"value": "Shiseido_ExpertChat",
			"transcriptFields":[ "Page_Type__c" ]
		});
	}

	console.log('start chat');
	//embedded_svc.liveAgentAPI.startChat();
	document.querySelector('.helpButtonEnabled').click();
	hideStorefrontCtas();
	gaEventCapture(siteLocation, 'Chat Button Clicked');
}

var initESW = function(gslbBaseURL) {
	// embedded_svc.settings.displayHelpButton = true; //Or false
	embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
	embedded_svc.settings.autoOpenPostChat = false;
	embedded_svc.settings.externalScripts = ["CustomEvents_fileTransferCustToAgent"];

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

		
	});

	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);

	//set pageType and blinking
	function constructPrechatDetails(){

		console.log('onloadFunction constructPrechatDetails initiated');
		
		 // let pageType = window["pageContext"] ? window["pageContext"].type : '';
         let 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 = '';
        }

		embedded_svc.settings.extraPrechatFormDetails = [{  
			"value": pageType,
			"transcriptFields":[ "Page_Type__c" ]
		},{
			"value": enterpriseCode,
			"transcriptFields":[ "Enterprise_Code__c" ]
		},{
			"value": brand,
			"transcriptFields":[ "Brand__c" ]
		},{
            "label":"MostRecentlyViewedPage",
            "value":window.location.href,
            "transcriptFields":[ "MostRecentlyViewedPage__c" ],
            "displayToAgent":true
        }
	];

		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;
			// if (enterpriseCode == 'NARS-US') {
			let button = document.querySelectorAll('.sfsc-chat-cta-agent, .sfsc-chat-cta-artist, .sfsc-chat-banner, .live-chat');
			// } else if (enterpriseCode == 'CPB-US') {
			// 	button = document.querySelectorAll('.sfsc-chat-banner');
			// } else if (enterpriseCode == 'SHI-US') {
			// 	button = document.querySelectorAll('.sfsc-chat-cta-agent');
			// }
			for (let i=0; i<button.length; i++) {
				button[i].classList.add('blinking');
			}
			
			embedded_svc.settings.extraPrechatFormDetails = [{  
				"value": true,
				"transcriptFields":[ "Clicked_Button_Blinking__c" ]
			},{  
				"value": window["pageContext"].title,
				"transcriptFields":[ "Page_Type__c" ]
			},{
				"value": enterpriseCode,
				"transcriptFields":[ "Enterprise_Code__c" ]
			},{
				"value": brand,
				"transcriptFields":[ "Brand__c" ]
			}];
			// message = document.getElementsByClassName("message");
			// if(window["pageContext"].title == "Cart"){
			// 	message[0].innerHTML = 'Cart Assistance';
			// }else if(window["pageContext"].title == "SinglePageCheckout"){
			// 	message[0].innerHTML = 'Checkout Assistance';
			// }else{
			// 	message[0].innerHTML = 'Chat with Us'; 
			// }
			setTimeout(function(){
				for (let i=0; i<button.length; i++) {
					button[i].classList.remove('blinking');
				}
			}, msToBlink * 1000);
		}, msToWait * 1000);
	}

	//used to stop blinking after chat starts 
	embedded_svc.addEventHandler('onChatRequestSuccess', stopBlinking)
    function stopBlinking(){
		let button = document.querySelectorAll('.sfsc-chat-cta-agent, .sfsc-chat-cta-artist, .sfsc-chat-banner, .live-chat');
		for (let i=0; i<button.length; i++) {
			button[i].classList.remove('blinking');
		}
    }
	//end of blinking solution

	//Rebuild chat button after ESD destroyed
	embedded_svc.addEventHandler('afterDestroy', reinitializeChat)
	function reinitializeChat(){
		showStorefrontCtas();
		needsStartGaEvent = true;
	}
	//End rebuild ESD

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

	embedded_svc.addEventHandler("onAgentMessage", function(data) {
		setAssistantLabels();
	});

	embedded_svc.addEventHandler("onQueueUpdate", function(data) {
		if (data.queuePosition == 0) {
			gaEventCapture(siteLocation, "Chat Accepted");
		}
	});
	//End listeners for GA Event Capture

	//Set Avatars, Logos, Labels
	if(esdConfig.chatbotAvatar){
		embedded_svc.settings.chatbotAvatarImgURL = esdConfig.chatbotAvatar;
	}
	if(esdConfig.headerLogo){
		embedded_svc.settings.smallCompanyLogoImgURL =esdConfig.headerLogo;
	}

	embedded_svc.settings.enabledFeatures = ['LiveAgent'];
	embedded_svc.settings.entryFeature = 'LiveAgent';

	embedded_svc.init(
		esdEnvironmentUrl,
		esdSiteHostURL,
		gslbBaseURL,
		orgId,
		esdConfig.esdDevName,
		{
			baseLiveAgentContentURL: esdConfig.baseLiveAgentContentURL,
			deploymentId: esdConfig.deploymentId,
			buttonId: esdConfig.buttonId,
			baseLiveAgentURL: esdConfig.baseLiveAgentURL,
			eswLiveAgentDevName: esdConfig.eswLiveAgentDevName,
			isOfflineSupportEnabled: false
		}
	);
};

if (!window.embedded_svc) {
	var s = document.createElement('script');
	s.setAttribute('src', esdEnvironmentUrl + '/embeddedservice/5.0/esw.min.js');
	s.onload = function() {
		initESW(null);
	};
	console.log('building ESD');
	document.body.appendChild(s);
} else {
	initESW('https://service.force.com');
}

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

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

	if(consentSelection.detail.message === 'Consent Disagree'){
		embedded_svc.liveAgentAPI.endChat();
	}
}