// Cookie consent banner & third-party analytics loader
// - Stores preference in localStorage
// - Shows a bottom banner until user accepts or rejects
// - Loads Google Analytics and Microsoft Clarity only when accepted

(function () {
    'use strict';

    var STORAGE_KEY = 'mifi-ventures-cookie-consent';
    var BANNER_ID = 'cookie-banner';
    var BANNER_VISIBLE_CLASS = 'is-visible';
    var hasLoadedThirdParty = false;

    // Trusted Types support (for CSP `require-trusted-types-for 'script'`)
    // Clarity's tag script looks up window.trustedTypePolicies[policyName] to load its inner script;
    // we must expose the policy there for Safari (and other browsers) to avoid TT violations.
    var ttPolicy = null;
    try {
        if (
            window.trustedTypes &&
            typeof window.trustedTypes.createPolicy === 'function'
        ) {
            ttPolicy = window.trustedTypes.createPolicy('mifi-ventures-policy', {
                createScriptURL: function (url) {
                    return url;
                },
            });

            if (ttPolicy && !window.trustedTypePolicies) {
                window.trustedTypePolicies = {};
            }

            if (ttPolicy) {
                window.trustedTypePolicies['mifi-ventures-policy'] = ttPolicy;
            }
        }
    } catch (_) {
        ttPolicy = null;
    }

    function setScriptSrc(el, url) {
        if (!el) return;
        if (ttPolicy) {
            // When Trusted Types are enforced, wrap URLs via our policy
            el.src = ttPolicy.createScriptURL(url);
        } else {
            el.src = url;
        }
    }

    function loadThirdPartyAnalytics() {
        if (hasLoadedThirdParty) return;
        hasLoadedThirdParty = true;

        // Google Analytics (gtag.js + ga-init.js)
        try {
            var gtagScript = document.createElement('script');
            gtagScript.async = true;
            setScriptSrc(
                gtagScript,
                'https://www.googletagmanager.com/gtag/js?id=G-36F29PDKRT',
            );

            gtagScript.onload = function () {
                // Load the existing ga-init.js helper once gtag is ready
                var gaInit = document.createElement('script');
                gaInit.defer = true;
                setScriptSrc(gaInit, '/assets/js/ga-init.js');
                document.head.appendChild(gaInit);
            };

            document.head.appendChild(gtagScript);
        } catch (e) {
            // Fail silently – analytics are non-essential
            console.error('Failed to load Google Analytics', e);
        }

        // Microsoft Clarity – use the official loader snippet so that
        // window.clarity is defined before the tag script runs.
        try {
            (function (c, l, a, r, i, t, y) {
                c[a] =
                    c[a] ||
                    function () {
                        (c[a].q = c[a].q || []).push(arguments);
                    };
                t = l.createElement(r);
                t.async = 1;
                setScriptSrc(
                    t,
                    `https://www.clarity.ms/tag/${i}?trustedTypes=mifi-ventures-policy`,
                );
                y = l.getElementsByTagName(r)[0];
                y.parentNode.insertBefore(t, y);
            })(window, document, 'clarity', 'script', 'vuo5q3yf79');

            window.clarity('consentv2', {
                ad_Storage: 'granted',
                analytics_Storage: 'granted',
            });
        } catch (e2) {
            console.error('Failed to load Microsoft Clarity', e2);
        }
    }

    function hideBanner(banner) {
        if (!banner) return;
        banner.classList.remove(BANNER_VISIBLE_CLASS);
    }

    function showBanner(banner) {
        if (!banner) return;
        banner.classList.add(BANNER_VISIBLE_CLASS);
    }

    function init() {
        var banner = document.getElementById(BANNER_ID);
        if (!banner) return;

        var acceptBtn = banner.querySelector('[data-consent="accept"]');
        var rejectBtn = banner.querySelector('[data-consent="reject"]');

        var pref;
        try {
            pref = window.localStorage.getItem(STORAGE_KEY);
        } catch (_) {
            pref = null;
        }

        if (pref === 'accept') {
            hideBanner(banner);
            loadThirdPartyAnalytics();
        } else if (pref === 'reject') {
            hideBanner(banner);
        } else {
            showBanner(banner);
        }

        if (acceptBtn) {
            acceptBtn.addEventListener('click', function () {
                try {
                    window.localStorage.setItem(STORAGE_KEY, 'accept');
                } catch (_) {
                    // ignore
                }
                hideBanner(banner);
                loadThirdPartyAnalytics();
            });
        }

        if (rejectBtn) {
            rejectBtn.addEventListener('click', function () {
                try {
                    window.localStorage.setItem(STORAGE_KEY, 'reject');
                } catch (_) {
                    // ignore
                }
                hideBanner(banner);
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
