function createCnLangConfigHelper(windowObj, documentObj, ShopifyObj, config) {
    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;
        }

        executeWhenCnHelperIsReady(() => {
            windowObj.cnHelper.addConnectifIsTrackedPurchase(false);
        });
    }

    function injectConnectif(storeConfig) {
        executeWhenCnHelperIsReady(() => {
            const cartAttributes = {
                connectifStoreId: storeConfig.connectifStoreId,
                connectifClientId: storeConfig.clientId,
                connectifApiUrl: storeConfig.connectifApiUrl,
                isTrackedPurchase: true
            };
            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/eu1/client-script/0caaf205-3b91-4da1-aa93-9f8232c45961","lang":"es","currency":"EUR","connectifStoreId":"67c1a58e3fe20790ad630d4f","connectifApiUrl":"https://eu1-api.connectif.cloud","clientId":"0caaf205-3b91-4da1-aa93-9f8232c45961","marketCountryCodes":["ES"]}];
    createCnLangConfigHelper(window, window.document, window.Shopify, config);
})(window);

// Export the function for use in tests
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = { createCnLangConfigHelper };
}
