document.addEventListener("DOMContentLoaded", function () {
    const banner = document.getElementById("cookie-banner");
    const acceptBtn = document.getElementById("accept-cookies");
    const rejectBtn = document.getElementById("reject-cookies");

    // Check if consent is already given
    if (localStorage.getItem("cookieConsent") === "accepted") {
        enableTracking();
        banner.style.display = "none";
    } else if (localStorage.getItem("cookieConsent") === "rejected") {
        banner.style.display = "none";
    }

    // Accept Cookies
    acceptBtn.addEventListener("click", function () {
        localStorage.setItem("cookieConsent", "accepted");
        enableTracking();
        banner.style.display = "none";
    });

    // Reject Cookies
    rejectBtn.addEventListener("click", function () {
        localStorage.setItem("cookieConsent", "rejected");
        banner.style.display = "none";
    });

    enableTracking();

    function enableTracking() {
        // Google Analytics
        if (GOOGLE_ANALYTICS_ID !== "UA-XXXXXXXXX-X") {
            let gaScript = document.createElement("script");
            gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${GOOGLE_ANALYTICS_ID}`;
            document.body.appendChild(gaScript);
            gaScript.onload = function () {
                window.dataLayer = window.dataLayer || [];
                function gtag() { dataLayer.push(arguments); }
                gtag("js", new Date());
                gtag("config", GOOGLE_ANALYTICS_ID, { anonymize_ip: true });
            };
        }

        // Microsoft Clarity
        if (MICROSOFT_CLARITY_ID !== "XXXXXXXXX") {
            let clarityScript = document.createElement("script");
            clarityScript.innerHTML = `(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; t.src="https://www.clarity.ms/tag/"+i; y=l.getElementsByTagName(r)[0]; y.parentNode.insertBefore(t,y); })(window, document, "clarity", "script", "${MICROSOFT_CLARITY_ID}");`;
            document.body.appendChild(clarityScript);
        }

        // Facebook Pixel
        if (FACEBOOK_PIXEL_ID !== "YOUR_FACEBOOK_PIXEL_ID") {
            let fbScript = document.createElement("script");
            fbScript.innerHTML = `!function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
            if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
            n.queue=[];t=b.createElement(e);t.async=!0;
            t.src=v;s=b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t,s)}(window, document,'script',
            'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', '${FACEBOOK_PIXEL_ID}'); 
            fbq('track', 'PageView');`;
            document.body.appendChild(fbScript);
        }
    }
});
