import { onPageLoadComplete } from '@nimius/event-utility';
import { extractPrefixedAttributesFromElement } from '@nimius/dom-utility';
import { initCookieConsent } from './cookie-consent';

// The name of the data attribute identifing the target node.
const targetNodeDataAttribute = 'data-site-tracking';

// Parallel testing of Google Analytics 4
const targetNodeDataAttributeGTag = 'data-site-tracking-gtag';

// Wait for page load is completed.
onPageLoadComplete(async () => {
    // Select node for which the script needs to be executed.
    const siteTrackingNode = document.querySelector(`[${targetNodeDataAttribute}]`);

    // Only proceed if target node is found in the DOM.
    if (siteTrackingNode) {
        // eslint-disable-next-line max-len
        const { initSiteTracking } = await import(/* webpackChunkName: "site-tracking" */ '../site-tracking/index');
        const settings = extractPrefixedAttributesFromElement(siteTrackingNode, `${targetNodeDataAttribute}-`);

        /*eslint-disable*/
        console.log(settings);
        /*eslint-enable*/

        initSiteTracking(settings);

        // Parallel testing of Google Analytics 4
        if (document.querySelector(`[${targetNodeDataAttributeGTag}]`) != null) {
            const siteTrackingNodeGTag = document.querySelector(`[${targetNodeDataAttributeGTag}]`);
            const settingsGTag = extractPrefixedAttributesFromElement(siteTrackingNodeGTag, `${targetNodeDataAttributeGTag}-`);

            initSiteTracking(settingsGTag);
        }

        // make sure this is executed after site tracking is initialized
        initCookieConsent();
    } else {
        initCookieConsent();
    }
});
