let availiabilityapi = 'https://motorolasolutions.my.site.com/channel/services/apexrest/getMockAvailability?agentavailability=false';
let loaded = 0;
let isConnected = false;
let isOnline = false;
let isHeaderClick = false;
let isChatButtonClicked = false;
let bannerConfig;
let embeddedLayout;
let isAuthenticated;
const siteUrl = window.location.href;
const siteLang = window.location.href.split('/')[3].toLowerCase().replace(/\.html.*/, '');
const APP_MINIMIZE_EVENT_NAME = 'ESW_APP_MINIMIZE';
const APP_MAXIMIZE_EVENT_NAME = 'ESW_APP_MAXIMIZE';

function getScriptPath(){
    let sc = document.currentScript;
    let path;
    if (sc.src.indexOf('/LiveAgentHebrewJs') > 0) {
        path = sc.src.split("/LiveAgentHebrewJs")[0];
    } else if (sc.src.indexOf('LiveAgentAllLocalesJs') > 0) {
        path = sc.src.split("/LiveAgentAllLocalesJs")[0];
    } else if (sc.src.indexOf('LiveAgentEnglishBotJs') > 0) {
        path = sc.src.split("/LiveAgentEnglishBotJs")[0];
    } else {
        path = sc.src.split("/LiveAgentBotJs")[0];
    }
    return path;
}

function loadScript(path,scriptName){
    let head = document.getElementsByTagName('HEAD')[0];
    let link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = path + '/' + scriptName + '?t=' + Date.now();
    head.appendChild(link);
}

function loadCssScripts(){
    loadScript(getScriptPath(), 'LiveAgentCommonCss');
    if(window.location.href.includes('/en_us/') || window.location.href.includes('/en_us.html')){
        loadScript(getScriptPath(), 'LiveAgentEnglish');
    } else if(window.location.href.includes('/he_il/') || window.location.href.includes('/he_il.html')) {
        loadScript(getScriptPath(), 'LiveAgentHebrew');
    }
}
loadCssScripts();

function getKeyword(site_url) {
    let key_value = '';
    const mapped_site_to_keyword = new Map();
    mapped_site_to_keyword.set('namrinfo', 'ELOQUA_NAMRINFO');
    mapped_site_to_keyword.set('eloqua', 'ELOQUAMSI');
    mapped_site_to_keyword.set('blog', 'NAMSI');
    mapped_site_to_keyword.set('content/static/sr', 'NAMSI');
    mapped_site_to_keyword.set('shop', 'SHOP');
    mapped_site_to_keyword.set('watchguard', 'WATCHGUARD');
    mapped_site_to_keyword.set('partner-central', 'NAPC');

    for (const ky of mapped_site_to_keyword.keys()) {
        if (site_url.includes(ky)) {
            key_value = mapped_site_to_keyword.get(ky);
            break;
        }
    }
    return key_value;
}

// This is for AEM pages
function setCountry() {
    let country = "";
    fetch(document.location, { method: 'HEAD' })
        .then(function(response) {
            country = response.headers.get('Imperva-Viewer-Country');
        })
        .catch(function(error) {
            console.error('Error fetching country:', error);
        });

    return country;
}


function setEmptyOrValue(field_value) {
    field_value = (field_value == null || field_value == 'null') ? '' : field_value;
    return field_value;
}

function getParameterValue(attribute_value) {
    return document.getElementById('msi-uinfo') ? document.getElementById('msi-uinfo').getAttribute(attribute_value) : '';
}

function getLoginId() {
    let login_id = getParameterValue('data-ulogin');
    if (!login_id) {
        login_id = getParameterValue('data-uid')
    }
    return setEmptyOrValue(login_id);
}

function getLocale() {
    let locale_value = getParameterValue('data-ulocale');
    if (!locale_value) {
        locale_value = utag_data['locale'];
    }
    return setEmptyOrValue(locale_value);
}

function getFirstName() {
    let first_name = getParameterValue('data-ufirstname')
    if (!first_name) {
        first_name = getCookie('first_name');
    }
    return setEmptyOrValue(first_name);
}

function getLastName() {
    let last_name = getParameterValue('data-ulastname');
    if (!last_name) {
        last_name = getCookie('last_name');
    }
    return setEmptyOrValue(last_name);
}

function getCountry() {
    let country_value = countryCode;
    if (!country_value) {
        country_value = navigator.language.includes('-') ? navigator.language.split('-')[1] : '';
    }
    if (!country_value) {
        country_value = navigator.language.includes('_') ? navigator.language.split('_')[1] : '';
    }
    return setEmptyOrValue(country_value.toUpperCase());
}

function getEmail() {
    let emailVal = getParameterValue('data-uemail')
    return setEmptyOrValue(emailVal);
}

function getUserType() {
    let user_type = getParameterValue('data-utype');
    if (!user_type) {
        user_type = getCookie('usertype');
    }

    if (user_type) {
        user_type = getNormalizedUserType(user_type);
    }
    return setEmptyOrValue(user_type);
}

function getNormalizedUserType(user_type) {
    const usertype_map = new Map();
    usertype_map.set('PARTNER', 'PARTNER');
    usertype_map.set('CONSUMER', 'CONSUMER');
    usertype_map.set('DIRECT', 'CUSTOMER');
    usertype_map.set('SALES', 'EMPLOYEE');
    usertype_map.set('INTERNAL', 'EMPLOYEE');
    usertype_map.set('DEFAULT', 'CONSUMER');
    return usertype_map.get(user_type);
}

function getNormalizedRegion(region) {
    const region_map = new Map();
    region_map.set('NA', 'NA');
    region_map.set('NAMR', 'NA');
    region_map.set('NORTH AMERICA', 'NA');
    region_map.set('EA', 'EA');
    region_map.set('EMEA', 'EA');
    region_map.set('LA', 'LA');
    region_map.set('LACR', 'LA');
    region_map.set('AP', 'AP');
    region_map.set('APAC', 'AP');
    region_map.set('ANZ', 'AP');
    region_map.set('ASIA PACIFIC', 'AP');
    region_map.set('EUROPE', 'EA');
    region_map.set('LATIN AMERICA', 'LA');
    region_map.set('MIDDLE EAST', 'EA');
    return region_map.get(region);
}

function getCountryMapRegion(country) {
    let country_region_map = new Map();
    country_region_map.set('AE', 'EA'); // UNITED ARAB EMIRATES
    country_region_map.set('AR', 'LA'); // ARGENTINA
    country_region_map.set('AU', 'AP'); // AUSTRALIA
    country_region_map.set('BR', 'LA'); // BRAZIL
    country_region_map.set('CA', 'NA'); // CANADA
    country_region_map.set('CL', 'LA'); // CHILE
    country_region_map.set('CN', 'AP'); // CHINA
    country_region_map.set('CO', 'LA'); // COLOMBIA
    country_region_map.set('DE', 'EA'); // GERMANY
    country_region_map.set('DK', 'EA'); // DENMARK
    country_region_map.set('EC', 'LA'); // ECUADOR
    country_region_map.set('ES', 'EA'); // SPAIN
    country_region_map.set('FR', 'EA'); // FRANCE
    country_region_map.set('GB', 'EA'); // UNITED KINGDOM
    country_region_map.set('ID', 'AP'); // INDONESIA
    country_region_map.set('IL', 'EA'); // ISRAEL
    country_region_map.set('IN', 'AP'); // INDIA
    country_region_map.set('IT', 'EA'); // ITALY
    country_region_map.set('JP', 'AP'); // JAPAN
    country_region_map.set('KP', 'AP'); // DEMOCRATIC PEOPLE'S REPUBLIC OF KOREA
    country_region_map.set('KR', 'AP'); // REPUBLIC OF KOREA
    country_region_map.set('MX', 'LA'); // MEXICO
    country_region_map.set('MY', 'AP'); // MALAYSIA
    country_region_map.set('NL', 'EA'); // NETHERLANDS
    country_region_map.set('NO', 'EA'); // NORWAY
    country_region_map.set('PE', 'LA'); // PERU
    country_region_map.set('PH', 'AP'); // PHILIPPINES
    country_region_map.set('PL', 'EA'); // POLAND
    country_region_map.set('RU', 'EA'); // RUSSIAN FEDERATION
    country_region_map.set('SA', 'AP'); // SAUDI ARABIA
    country_region_map.set('SG', 'AP'); // SINGAPORE
    country_region_map.set('TW', 'AP'); // TAIWAN
    country_region_map.set('UA', 'EA'); // UKRAINE
    country_region_map.set('US', 'NA'); // UNITED STATES
    country_region_map.set('VN', 'AP'); // VIETNAM
    country_region_map.set('ZA', 'EA'); // SOUTH AFRICA

    country_region_map.set('419', 'LA'); // LOCALE CODE
    country_region_map.set('XA', 'AP'); // LOCALE CODE
    country_region_map.set('XC', 'EA'); // LOCALE CODE
    country_region_map.set('XL', 'LA'); // LOCALE CODE
    country_region_map.set('XP', 'AP'); // LOCALE CODE
    country_region_map.set('XU', 'EA'); // LOCALE CODE

    return country_region_map.get(country);
}

function getRegion() {
    let region = getParameterValue('data-uregion');
    if (!region) {
        region = getCookie('region');
    }
    if (!region) {
        let locale = getLocale();
        if (locale) {
            region = getCountryMapRegion(locale.substring(3).toUpperCase());
        }
    }
    if (!region) {
        let country_value = getCountry();
        if (country_value) {
            region = getCountryMapRegion(country_value);
        }
    }
    if (!region) {
        region = 'NA';
    }
    return getNormalizedRegion(region.toUpperCase());
}


function getCookie(name) {
    let cookie = {};
    document.cookie.split(';').forEach(function (el) {
        let [k, v] = el.split('=');
        cookie[k.trim()] = v;
    })
    return cookie[name];
}

function eraseCookie(name) {
    document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

if (getCookie("IsBannerLoaded") == undefined) {
    document.cookie = "IsBannerLoaded=1;Domain=motorolasolutions.com;";
}

/*** Close button on Alert ***/
let sfclose = document.getElementById('sfclose');
let sfpop = document.getElementById('sfchatbanner');

if (sfclose) {
    sfclose.addEventListener('click', function () {
        sfpop.classList.remove('active');
    });
}

function setRightToLeft(domObject) {
    if (siteLang == 'he_il') {
        domObject.attr('dir', 'rtl')
    }
}

function shouldOpenBanner() {
    return $('.helpButtonEnabled').length && !$('.messageContent').length && loaded === 0 && Boolean(bannerConfig.enabled);
}

function isBannerActive() {
    return document.getElementById('sfchatbanner').classList.contains('active');
}

function getGAClientId() {
    let gaClientId = '';
    if (utag_data['cp._ga']) {
        let gaId = utag_data['cp._ga']?.split('.');
        let size = gaId.length;
        if (size == 4) {
            gaClientId = gaId[size - 2] + '.' + gaId[size - 1];
        }
    }
    return gaClientId;
}

function setBannerContent(bannerId, bannerText) {
    $(bannerId).html(bannerText);
}

function getSiteUserType() {
    return getUserType() || 'GUEST';
}

function parseBannerConfig(bannerConfig) {
    return JSON.parse(bannerConfig);
}

function updateButtonId(configResp, siteUserType, bannerConfig) {
    const banner = getBannerForUserType(bannerConfig, siteUserType);
    if (!banner) return;

    updateButtonIdBasedOnBanner(configResp, banner, siteUserType);
    handleBannerLoad(banner);
}

function getBannerForUserType(bannerConfig, siteUserType) {
    for (const bannerConfigIterable of bannerConfig) {
        if (bannerConfigIterable[siteUserType]) {
            return bannerConfigIterable[siteUserType];
        }
    }
    return null; // Return null if no banner for the siteUserType
}

function updateButtonIdBasedOnBanner(configResp, bannerConfig, siteUserType) {
    if (siteUserType === 'PARTNER' && Boolean(bannerConfig.alterRouting)) {
        configResp.Button_Id__c = bannerConfig.alterRouting;
    }
}

function handleBannerLoad(bannerConfig) {
    if (getCookie('IsBannerLoaded') === '1' && loaded === 0) {
        loaded = 1;
        setTimeout(function () {
            if (!isChatButtonClicked) {
                document.getElementById('sfchatbanner').classList.add('active');
                loaded = 1;
                eraseCookie('IsBannerLoaded');
                document.cookie = 'IsBannerLoaded=0;Domain=motorolasolutions.com;';
            }
        }, bannerConfig.start_delay_time_ms);
    }
}

function capitalizeFirstLetter(str) {
    return str[0].toUpperCase() + str.slice(1);
}

function handleChatBanner() {
    const sfchatbanner = document.getElementById('sfchatbanner');
    if (sfchatbanner.classList.contains('active')) {
        sfchatbanner.classList.remove('active');
    }
}



const countryCode = setCountry();
const moca_keyword = (siteLang == 'en_us') ? getKeyword(siteUrl) : '';
const locale = getLocale() ? getLocale() : "_DEFAULT";
const country = countryCode || "_DEFAULT";
const region = getRegion() ? getRegion() : "";

const endPoint = (siteLang == 'en_us') ? 'einsteinconfigurl' : 'liveagentconfigurl';
const site_end_point_url = 'https://motorolasolutions.my.site.com/channel/services/apexrest/' + endPoint + '?localename=' + locale + '&keyword=' + moca_keyword + '&region=' + region + '&country=' + country;

function handleSuccess(configResp) {
	let bannerText = configResp.Banner_Text__c;
    bannerConfig = configResp.Popup_Banner_Config__c;
	setBannerContent('#bannerId', bannerText);
    const siteUserType = getSiteUserType();
    const parsedBannerConfig = parseBannerConfig(bannerConfig);
    updateButtonId(configResp, siteUserType, parsedBannerConfig);
}

//New en_us js logic
// Configuration object for all regions
const regionConfig = [
    {
        countries: ['_DEFAULT', 'US', 'AG', 'AW', 'BS', 'BB', 'BZ', 'CW', 'DM', 'GD', 'GY', 'HT', 'JM', 'KN', 'LC', 'VC', 'SR', 'TT', 'BM', 'KY', 'MF', 'VI', 'AI', 'BL', 'BQ', 'GF', 'MS', 'SX', 'TC', 'VG', 'GP'],
        locales: ['us', 'en_us', 'en_xl', 'es_419', 'pt_br', 'pt_xl'],
        region: 'LA',
        esdValue: 'LACR_Marketing_Car_And_Br'
    },
    {
        countries: ['CO', 'CR', 'DO', 'EC', 'SV', 'GT', 'HN', 'NI', 'PA', 'VE', 'PR', 'CL', 'AR', 'BO', 'PY', 'PE', 'UY'],
        locales: ['us', 'en_us', 'en_xl', 'es_419', 'es_xl', 'es_mx', 'pt_br', 'pt_xl'],
        region: 'LA',
        esdValue: 'LACR_Marketing_NOLA'
    },
    {
        countries: ['MX', '_DEFAULT', 'US'],
        locales: ['us', 'en_us', 'en_xl', 'es_419', 'es_xl', 'es_mx', 'pt_br', 'pt_xl'],
        region: 'LA',
        esdValue: 'LACR_Marketing_MX'
    },
    {
        countries: ['_DEFAULT', 'US'],
        locales: ['us', 'de_de', 'de_xc', 'en_us', 'en_xu', 'es_es', 'fr_fr', 'it_it', 'pl_pl', 'he_il', 'uk_ua', 'ru_ru'],
        region: 'EA',
        esdValue: 'EMEA_Customer_Care_Spa'
    },
    {
        countries: ['_DEFAULT', 'US'],
        locales: ['zh_cn', 'en_us', 'en_xp', 'en_xa', 'us', 'zh_tw'],
        region: 'AP',
        esdValue: 'APAC_Customer_Care_Eng'
    },
    {
        countries: ['_DEFAULT', 'US'],
        locales: ['ja_jp', 'ko_kp', 'ko_kr'],
        region: 'AP',
        esdValue: 'APAC_Customer_Care_Jap'
    },
    {
        countries: ['_DEFAULT', 'US'],
        locales: ['_DEFAULT', 'US', 'en_us'],
        region: 'NA',
        esdValue: 'Miaw_Chat'
    }
];
const langCountryArray = ['ko_kp', 'ko_kr', 'es_es', 'es_xl', 'pt_xl', 'en_xu', 'fr_fr', 'de_xc', 'de_de', 'he_il', 'it_it', 'pl_pl',
'ru_ru', 'uk_ua', 'es_mx', 'en_xl', 'en_xa', 'ja_jp', 'es_mx', 'en_sg', 'en_xp'];

// The consolidated map
const comboEsdMap = new Map();

// Populate the map using the configuration
regionConfig.forEach(({ countries, locales, region, esdValue }) => {
    countries.forEach(country => {
        locales.forEach(locale => {
            const key = `${country}--${region}--${locale}`;
            comboEsdMap.set(key, esdValue);
        });
    });
});

/* Salesforce org-level configuration */
let config = {
    'orgId': '00D300000000zOc',
    'siteUrl': 'https://motorolasolutions.my.site.com',
	'scrt2URL': 'https://motorolasolutions.my.salesforce-scrt.com',
};

/* Country-wise ESD configuration */
let options = {
    'APAC_Customer_Care_Eng': {
        'LWRSiteId': '1736171612442'
    },
    'APAC_Customer_Care_Jap': {
        'LWRSiteId': '1736180318797'
    },
    'EMEA_Customer_Care_Spa': {
        'LWRSiteId': '1736181738493'
    },
    'APAC_Customer_Care_Kor': {
        'LWRSiteId': '1736181291225'
    },
    'LACR_Marketing_MX': {
        'LWRSiteId': '1736181563990'
    },
    'LACR_Marketing_Car_And_Br': {
        'LWRSiteId': '1736181291225'
    },
    'LACR_Marketing_SOLA': {
        'LWRSiteId': '1734100645030'
    },
    'LACR_Marketing_NOLA': {
        'LWRSiteId': '1736181371348'
    },
    'Miaw_Chat':{
        'LWRSiteId': '1733729176007'
    }
};
let messagingChannelUrl;
let guid = '';



function isGuestSiteUser() {
    return window.ChatConfig.User.User_License__c === 'Guest User License';
}

function areWeOnCommunityPage() {
    let urlHref = window.location.hostname.toLowerCase();
    return (urlHref.includes('support') || urlHref.includes('partner') || urlHref.includes('customer'));
}

function whatCommunityAreWeOn() {
    let urlHref = window.location.href.toLowerCase();
    if (urlHref.includes('support') && !urlHref.includes('customer')) {
        return 'Support';
    }
    if (urlHref.includes('customer')) {
        return 'Customer';
    }
    if (urlHref.includes('partner')) {
        return 'Partner';
    }
}

function initEmbeddedMessaging(config) {
    try {
        let locale = getLocale();
		if(locale.toLowerCase() === 'en_us')
			embeddedservice_bootstrap.settings.language = config.language;
		else {
			let language = locale;
			if (langCountryArray.includes(language) && language.toLowerCase() !== 'en_us') {
				language = language.split('_')[0];
			}
			let nonConfigLanguage = (language !== undefined ? language : 'en');
			if (nonConfigLanguage === 'pt'){
			    nonConfigLanguage = 'pt_PT';
   			}
			embeddedservice_bootstrap.settings.language = nonConfigLanguage; // For example, enter 'en' or 'en-_DEFAULT'
		}
        embeddedservice_bootstrap.init(
            config.orgId,
            config.name,
            config.siteUrl, {
            scrt2URL: config.scrt2URL
        }
        );
    } catch (err) {
        console.error('Error loading Embedded Messaging: ', err);
    }
};

function loadJS(config, async = true) {
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = config.siteUrl + '/assets/js/bootstrap.min.js';
    script.onload = function () {
        //check if we are on aem page or a community pag
        let isCommunityPage = areWeOnCommunityPage();
        if (isCommunityPage) {
            //if on community we need to wait for chatConfig object to be available
            checkChatConfigObjectReady(config);
        }
        else {
            initEmbeddedMessaging(config);
        }
    };
    script.onerror = function (er) {
        console.error('error : ' + JSON.stringify(er));
    };
    document.body.appendChild(script);
}

window.addEventListener('onEmbeddedMessagingButtonCreated', e => {
    if (document.getElementById('embeddedMessagingConversationButton').style.display !== 'none')
    {
        document.getElementById('embedded-messaging').style.zIndex = '1000';
        fetch(site_end_point_url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Request failed with status: ' + response.status);
            }
            return response.text(); // or response.json() if the response is JSON
        })
        .then(data => {
            handleSuccess(JSON.parse(data))
        })
        .catch(error => {
            console.error('Error:', error);
        });
        availiabilityapi = "https://motorolasolutions.my.site.com/channel/services/apexrest/getMockAvailability?agentavailability=true";
        //AEM Header chat click
        document.addEventListener('chatclick', function ()
        {
            if (embeddedservice_bootstrap.utilAPI.getEmbeddedMessagingFrame()?.classList.contains('isMinimized'))
                embeddedservice_bootstrap.utilAPI.getEmbeddedMessagingFrame().contentWindow.postMessage({method:APP_MAXIMIZE_EVENT_NAME},config.siteUrl);
            else if (embeddedservice_bootstrap.utilAPI.getEmbeddedMessagingFrame()?.classList.contains('isMaximized'))
                embeddedservice_bootstrap.utilAPI.getEmbeddedMessagingFrame().contentWindow.postMessage({method:APP_MINIMIZE_EVENT_NAME},config.siteUrl);
            else
                document.querySelector('.embeddedMessagingConversationButton').click();
        })
    }
});

window.addEventListener('onEmbeddedMessagingReady', e => {
    handleEmbeddedMessagingReady();
});

function handleEmbeddedMessagingReady() {
    let isCommunityPage = areWeOnCommunityPage();
    let whichCommunity = whatCommunityAreWeOn();
    if (isCommunityPage) {
        handleCommunityPage(whichCommunity);
    } else {
        handleNonCommunityPage(whichCommunity);
    }
}

function handleCommunityPage(whichCommunity) {
    if (window.ChatConfig) {
        let isUnAuth = isGuestSiteUser();
        setVisiblePrechatFields(isUnAuth);
        setHiddenPrechatFields(whichCommunity, isUnAuth);
    }
}

function setVisiblePrechatFields(isUnAuth) {
    embeddedservice_bootstrap.prechatAPI.setVisiblePrechatFields({
        "_firstName": {
            "value": isUnAuth ? '' : (window.ChatConfig.User?.Contact?.FirstName || window.ChatConfig.User?.FirstName || ''),
            "isEditableByEndUser": isUnAuth ? true : (!window.ChatConfig.User?.Contact?.FirstName && !window.ChatConfig.User?.FirstName)
        },
        "_lastName": {
            "value": isUnAuth ? '' : (window.ChatConfig.User?.Contact?.LastName || window.ChatConfig.User?.LastName || ''),
            "isEditableByEndUser": isUnAuth ? true : (!window.ChatConfig.User?.Contact?.LastName && !window.ChatConfig.User?.LastName)
        },
        "_email": {
            "value": isUnAuth ? '' : (window.ChatConfig.User?.Contact?.Email || window.ChatConfig.User?.Email || ''),
            "isEditableByEndUser": isUnAuth ? true : (!window.ChatConfig.User?.Contact?.Email && !window.ChatConfig.User?.Email)
        }
    });
}

function setHiddenPrechatFields(whichCommunity, isUnAuth) {
    let authStatus = window.ChatConfig.User ? 'true' : 'false';
    const gaId = utag_data["cp._ga"]?.match(/\d{10}\.\d{10}/);
    embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
        "Language": window.ChatConfig.User?.LanguageLocaleKey,
        "LocaleCode": window.ChatConfig.User?.LanguageLocaleKey,
        "IsAuthenticated": authStatus,
        "GAClientId": gaId,
        "ContactId": window.ChatConfig.User?.ContactId,
        "SupportType": whichCommunity
    });
    if (whichCommunity !== 'Support') {
        embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
            "SourceURL": window.location.href.substring(0, 100)
        });
    }
}

function handleNonCommunityPage(whichCommunity) {
    embeddedservice_bootstrap.prechatAPI.setVisiblePrechatFields({
        "_firstName": {
            "value": getFirstName(),
            "isEditableByEndUser": true
        },
        "_lastName": {
            "value": getLastName(),
            "isEditableByEndUser": true
        },
        "_email": {
            "value": getEmail(),
            "isEditableByEndUser": true
        }
    });
    embeddedservice_bootstrap.prechatAPI.setHiddenPrechatFields({
        "SourceURL": window.location.href.split('?')[0] + '?region=' + getRegion(),
        "Language": config.language,
        "LocaleCode": getLocale(),
        "IsAuthenticated": !!getLoginId() ? 'true' : 'false',
        "GAClientId": getGAClientId(),
        "SupportType": whichCommunity,
        "Region": getRegion()
    });
}

async function checkChatConfigObjectReady(config) {
    try {
        while (true) {
            if (window.ChatConfig?.User) {
                initEmbeddedMessaging(config);
                break;
            }
            await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 5 seconds before checking again
        }
    } catch (error) {
        console.error('>> Error in checkChatConfigObjectReady : ', error);
    }
}

(function () {
    try {
        const locale = getLocale();
        if (locale.toLowerCase() != 'en_us') {
            configureNonEnglishSite();
        } else {
            configureEnglishSite();
        }
        window.addEventListener('onEmbeddedMessagingButtonClicked', e => {
            isChatButtonClicked = true;
            embeddedLayout = $("embedded_service_iframe-frame-layout");
            if (sfpop)
                sfpop.classList.remove('active');
        })
        messagingChannelUrl = config.siteUrl;
        //load the bootstrap file
        loadJS(config, false);
    }
    catch (ex) {
        console.error('Error loading Embedded Messaging: ', ex);
    }
})();

function configureNonEnglishSite() {
    let region = getRegion();
    const regex = /^en_/i;
    let locale = getLocale();
     if (regex.test(locale)) {
         if(region === 'LA'){
             locale = 'en_xl';
         }
     }
    let abbrSiteLang = locale;
    let country = region;
    const key = country.toUpperCase() + '--' + region + '--' + locale;
    let esd = comboEsdMap.get(key);
    if (!esd) {
        esd = findFallbackEsd(locale, region);
    }
    config.site = 'row';
    config.name = esd || 'Miaw_Chat';
    if(!esd){
        esd = 'Miaw_Chat';
    }
    if (langCountryArray.includes(country)) {
        country = country.split('_')[0];
    }
    if (langCountryArray.includes(abbrSiteLang)) {
        abbrSiteLang = abbrSiteLang.split('_')[0];
        if(abbrSiteLang == 'pt'){
            abbrSiteLang = 'pt_PT';
        }
    }
    config.langCountry = country;
    config.language = abbrSiteLang;
    config.siteUrl = config.siteUrl + '/' + getEsdName(esd, country);
}

function configureEnglishSite() {
    config.name = 'Miaw_Chat';
    config.language = 'en';
    config.siteUrl = config.siteUrl + '/ESWMiawChat1733729176007';
}

function findFallbackEsd(locale, region) {
    for (let [mapKey, mapValue] of comboEsdMap.entries()) {
        const parts = mapKey.split('--');
        if (parts.length === 3) {
            const keyRegion = parts[1];
            let keyLocale = parts[2];
            if (langCountryArray.includes(keyLocale)) {
                keyLocale = keyLocale.split('_')[0];
            }
            if (keyRegion === region && (keyLocale === locale || keyLocale.startsWith(`${locale}_`))) {
                return mapValue;
            }
        }
    }


    for (let [mapKey, mapValue] of comboEsdMap.entries()) {
        const keyLocale = mapKey.split('--').pop();
        if (keyLocale === locale || keyLocale.startsWith(`${locale}_`)) {
            return mapValue;
        }
    }
    return null;
}

function getEsdName(esd, country) {
    let esdName;
    let isWrongApiName = false;
    if (esd == 'LACR_Marketing_MX') {
        isWrongApiName = true;
        esd = 'EMEA_Customer_Care_Ger';
        esdName = 'ESW' + esd.replaceAll(' ', '').replaceAll('-', '').replaceAll('_', '') + options['LACR_Marketing_MX'].LWRSiteId;
    }
    if (esd == 'LACR_Marketing_Car_And_Br') {
        isWrongApiName = true;
        esd = 'APAC_Customer_Care_Kor';
        esdName = 'ESW' + esd.replaceAll(' ', '').replaceAll('-', '').replaceAll('_', '') + options['LACR_Marketing_Car_And_Br'].LWRSiteId;
    }
    if (esd == 'LACR_Marketing_SOLA') {
        isWrongApiName = true;
        esd = 'Miaw_Chat_Test';
        esdName = 'ESW' + esd.replaceAll(' ', '').replaceAll('-', '').replaceAll('_', '') + options['LACR_Marketing_SOLA'].LWRSiteId;
    }
    if (esd == 'LACR_Marketing_NOLA') {
        isWrongApiName = true;
        esd = 'APAC_Customer_Care_Man';
        esdName = 'ESW' + esd.replaceAll(' ', '').replaceAll('-', '').replaceAll('_', '') + options['LACR_Marketing_NOLA'].LWRSiteId;
    }
    if (!isWrongApiName) {
        esdName = 'ESW' + esd.replaceAll(' ', '').replaceAll('-', '').replaceAll('_', '') + options[esd].LWRSiteId;
    }
    return esdName;
}
