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 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}-`);

        initSiteTracking(settings);

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