document.addEventListener("DOMContentLoaded", function() {
    // Your GA4 Measurement ID
    const measurementId = 'G-FST06JC1TE';
    const consentKey = 'eba_analytics_consent';

    // 1. Check existing consent status
    const currentConsent = localStorage.getItem(consentKey);

    if (currentConsent === 'granted') {
        loadGoogleAnalytics();
    } else if (!currentConsent) {
        showBanner();
    }

    // 2. Manage Analytics button logic (binds to the footer link)
    const manageBtns = document.querySelectorAll('.js-manage-analytics');
    manageBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            localStorage.removeItem(consentKey);
            deleteCookies();
            alert("PRIVACY PROTOCOL EXECUTED: Analytics preferences reset. All tracking cookies have been purged from your browser.");
            location.reload(); // Reloads the page to prompt the banner again
        });
    });

    // 3. Construct and display the Brutalist consent banner
    function showBanner() {
        const banner = document.createElement('div');
        banner.id = 'cookie-consent-banner';
        
        // Inline styles to match your brutalist aesthetic (can be moved to consent.css)
        banner.style.position = 'fixed';
        banner.style.bottom = '0';
        banner.style.left = '0';
        banner.style.width = '100%';
        banner.style.backgroundColor = '#050505';
        banner.style.color = '#ffffff';
        banner.style.borderTop = '4px solid #d32f2f';
        banner.style.padding = '1.5rem 2rem';
        banner.style.zIndex = '9999';
        banner.style.display = 'flex';
        banner.style.flexDirection = 'column';
        banner.style.gap = '1.5rem';
        banner.style.fontFamily = "'IBM Plex Mono', 'Courier New', Courier, monospace";

        banner.innerHTML = `
            <div style="max-width: 1200px; margin: 0 auto; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 2rem; width: 100%;">
                <p style="margin: 0; font-size: 0.85rem; line-height: 1.5; flex: 1 1 600px;">
                    <strong style="color: #d32f2f;">PRIVACY PROTOCOL:</strong> We use strictly limited analytics to measure site performance. No clinical data is tracked. Do you consent to performance telemetry?
                </p>
                <div style="display: flex; gap: 1rem;">
                    <button id="accept-cookies" style="background-color: #d32f2f; color: #ffffff; border: 2px solid #d32f2f; padding: 0.75rem 1.5rem; font-family: inherit; font-weight: bold; cursor: pointer; transition: all 0.2s;">ACCEPT</button>
                    <button id="decline-cookies" style="background-color: transparent; color: #ffffff; border: 2px solid #64748b; padding: 0.75rem 1.5rem; font-family: inherit; font-weight: bold; cursor: pointer; transition: all 0.2s;">DECLINE</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(banner);

        document.getElementById('accept-cookies').addEventListener('click', function() {
            localStorage.setItem(consentKey, 'granted');
            banner.remove();
            loadGoogleAnalytics();
        });

        document.getElementById('decline-cookies').addEventListener('click', function() {
            localStorage.setItem(consentKey, 'denied');
            banner.remove();
        });
    }

    // 4. Inject GA4 securely
    function loadGoogleAnalytics() {
        const script = document.createElement('script');
        script.async = true;
        script.src = 'https://www.googletagmanager.com/gtag/js?id=' + measurementId;
        document.head.appendChild(script);

        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', measurementId, {
            'anonymize_ip': true, // Masks the final segment of user IP addresses
            'allow_google_signals': false // Permanently disables cross-device ad tracking
        });
    }

    // 5. Aggressive Cookie Deletion Routine
    function deleteCookies() {
        const cookies = document.cookie.split("; ");
        for (let c = 0; c < cookies.length; c++) {
            const d = window.location.hostname.split(".");
            while (d.length > 0) {
                const cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
                const p = location.pathname.split('/');
                document.cookie = cookieBase + '/';
                while (p.length > 0) {
                    document.cookie = cookieBase + p.join('/');
                    p.pop();
                }
                d.shift();
            }
        }
    }
});