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

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

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

            initSiteTracking(settings);
        }
    }

    initCookieConsent();
});
