export default () => {
    const body = document.querySelector('body');
    let analyticsId = body.getAttribute('data-analytics-id');
    let analyticsConfig = body.getAttribute('data-analytics-config');
    const appEnv = body.getAttribute('data-app-env');
    const defaultAnalyticsConfig = {
        'cookie_expires': 6 * 30 * 24 * 60 * 60,  // 6 months/180 days in seconds
        'anonymize_ip': true
    };

    if (!analyticsId || (appEnv !== null && appEnv !== 'prod')) {
        console.warn('GTM not initialized, missing analytics id or app env is not prod.');
        return;
    }

    window.gtag = window.gtag || function() {
        (window.dataLayer = window.dataLayer || []).push(arguments);
    };

    let config = defaultAnalyticsConfig;
    if (analyticsConfig) {
        config = {
            ...defaultAnalyticsConfig,
            ...JSON.parse(analyticsConfig)
        }
    }

    gtag('js', new Date());
    gtag('config', analyticsId, config);

    let gtmScript = document.createElement('script');
    gtmScript.classList.add('gtm-script');
    gtmScript.innerHTML = "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n" +
        "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n" +
        "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n" +
        "'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n" +
        "})(window,document,'script','dataLayer','" + analyticsId + "');";

    document.head.appendChild(gtmScript);

    let noScript = document.createElement('noscript');
    let iFrame = document.createElement('iframe');
    iFrame.src = "https://www.googletagmanager.com/ns.html?id=" + analyticsId;
    iFrame.style.display = 'none';
    iFrame.style.visibility = 'hidden';
    iFrame.style.height = '0px';
    iFrame.style.width = '0px';

    noScript.appendChild(iFrame);
    body.prepend(noScript);
}
