function createCnLangConfigHelper(
    windowObj,
    documentObj,
    ShopifyObj,
    config,
    cartCNContextAttributes
) {
    const readyStates = ['complete', 'interactive', 'loaded'];
    if (readyStates.indexOf(documentObj.readyState) >= 0) {
        onDocumentLoaded();
    } else {
        documentObj.addEventListener('DOMContentLoaded', onDocumentLoaded);
    }

    function onDocumentLoaded() {
        if (ShopifyObj) {
            const currentLang = ShopifyObj.locale;
            const currentCurrency = ShopifyObj.currency.active;
            const currentCountryCode = ShopifyObj.country;
            loadConnectifScript(currentLang, currentCurrency, currentCountryCode, config);
        } else {
            console.warn('Connectif could not be loaded, Shopify object is not available!');
        }
    }

    function loadConnectifScript(currentLang, currentCurrency, currentCountryCode, cnLangConfig) {
        const configsByLang = cnLangConfig.filter(cfg => cfg.lang === currentLang);
        const configsByCurrency = configsByLang.filter(cfg => cfg.currency === currentCurrency);
        const configsByCountry = configsByCurrency.filter(
            cfg => cfg.marketCountryCodes && cfg.marketCountryCodes.includes(currentCountryCode)
        );

        // Multiple matches by lang, currency and country should not be possible
        // Give priority to more specific settings that match
        // Only stores with selected currency AND language can have a market.
        if (configsByCountry.length > 0) {
            injectConnectif(configsByCountry[0]);
            return;
        }

        // It is possible that the store has a market configured but the country does not match,
        // in which case these stores should be discarded.
        const configsByCurrencyNoMarket = configsByCurrency.filter(
            cfg => !cfg.marketCountryCodes || cfg.marketCountryCodes.length === 0
        );
        if (configsByCurrencyNoMarket.length > 0) {
            injectConnectif(configsByCurrencyNoMarket[0]);
            return;
        }

        const configsWithoutCurrency = configsByLang.filter(
            cfg => !cfg.currency || cfg.currency === ''
        );
        if (configsWithoutCurrency.length > 0) {
            injectConnectif(configsWithoutCurrency[0]);
            return;
        }
    }

    function injectConnectif(storeConfig) {
        executeWhenCnHelperIsReady(() => {
            const cartAttributes = {
                connectifClientId: storeConfig.clientId,
                connectifApiUrl: storeConfig.connectifApiUrl
            };

            const hasChanged =
                cartCNContextAttributes.connectifClientId !== cartAttributes.connectifClientId ||
                cartCNContextAttributes.connectifApiUrl !== cartAttributes.connectifApiUrl;

            if (hasChanged) {
                windowObj.cnHelper.addCartAttributes(cartAttributes);
            }
        });
        createScriptTag(storeConfig.minifiedClientScriptUrl);
    }

    function executeWhenCnHelperIsReady(callback) {
        if (typeof windowObj.cnHelper === 'object') {
            callback();
        } else {
            documentObj.addEventListener('cnHelper.loaded', () => {
                callback();
            });
        }
    }

    function createScriptTag(scriptUrl) {
        const domCnScript = documentObj.createElement('script');
        domCnScript.type = 'text/javascript';
        domCnScript.async = true;
        domCnScript.src = scriptUrl;
        documentObj.head.appendChild(domCnScript);
    }
}

(function (window) {
    const config = [{"minifiedClientScriptUrl":"https://cdn.connectif.cloud/eu8/client-script/4336b378-e84d-4ad3-baff-f8cb4aec63f6","lang":"pt-PT","currency":"EUR","connectifStoreId":"672b604c9e89279dd4af3277","connectifApiUrl":"https://eu8-api.connectif.cloud","clientId":"4336b378-e84d-4ad3-baff-f8cb4aec63f6","marketCountryCodes":["PT"]},{"minifiedClientScriptUrl":"https://cdn.connectif.cloud/eu8/client-script/f8578f81-d75f-433a-bc22-1955e96c14e0","lang":"es","currency":"EUR","connectifStoreId":"6a8d8f611251d125231440c8","connectifApiUrl":"https://eu8-api.connectif.cloud","clientId":"f8578f81-d75f-433a-bc22-1955e96c14e0","marketCountryCodes":["ES"]},{"minifiedClientScriptUrl":"https://cdn.connectif.cloud/eu8/client-script/cd168178-6927-4c15-aca0-c249ccf9a011","lang":"fr","currency":"EUR","connectifStoreId":"6a8d8f821251d125231440c9","connectifApiUrl":"https://eu8-api.connectif.cloud","clientId":"cd168178-6927-4c15-aca0-c249ccf9a011","marketCountryCodes":["BE","FR","LU","GF","PF","TF"]},{"minifiedClientScriptUrl":"https://cdn.connectif.cloud/eu8/client-script/6367be2c-ed18-4ca7-b774-423a65e129c3","lang":"de","currency":"EUR","connectifStoreId":"6a8d8fa51251d125231440ca","connectifApiUrl":"https://eu8-api.connectif.cloud","clientId":"6367be2c-ed18-4ca7-b774-423a65e129c3","marketCountryCodes":["AT","DE"]},{"minifiedClientScriptUrl":"https://cdn.connectif.cloud/eu8/client-script/b512944a-5f3f-48bb-9344-5cc443136266","lang":"it","currency":"EUR","connectifStoreId":"6a8d8fce1251d125231440cb","connectifApiUrl":"https://eu8-api.connectif.cloud","clientId":"b512944a-5f3f-48bb-9344-5cc443136266","marketCountryCodes":["IT","SI"]}];
    const cartCNContextAttributes =
        typeof cartCNContext !== 'undefined'
            ? // eslint-disable-next-line no-undef
              cartCNContext.attributes
            : {
                  connectifClientId: null,
                  connectifApiUrl: null
              };
    createCnLangConfigHelper(
        window,
        window.document,
        window.Shopify,
        config,
        cartCNContextAttributes
    );
    // eslint-disable-next-line no-undef
})(window);

// Export the function for use in tests
// eslint-disable-next-line no-undef
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    // eslint-disable-next-line no-undef
    module.exports = { createCnLangConfigHelper };
}
