//User consent
document.addEventListener('DOMContentLoaded', function () {
    if (Cookies.get('seopress-user-consent-close') == undefined && Cookies.get('seopress-user-consent-accept') == undefined) {
        document.querySelectorAll('.seopress-user-consent.seopress-user-message, .seopress-user-consent-backdrop').forEach(function(element) {
            element.classList.remove('seopress-user-consent-hide');
        });
    }
    
	// Notify third-party listeners (e.g. Google Tag Manager) of the consent decision.
	const seopressNotifyConsent = function (consent) {
		window.dataLayer = window.dataLayer || [];
		window.dataLayer.push({ event: 'seopress_consent_updated', seopress_consent: consent });
		document.dispatchEvent(new CustomEvent('seopress.consent', { detail: { consent: consent } }));
	};

	const seopressUserConsentAcceptBtn = document.getElementById('seopress-user-consent-accept');
	if (seopressUserConsentAcceptBtn) seopressUserConsentAcceptBtn.addEventListener('click', function () {
        document.querySelectorAll('.seopress-user-consent.seopress-user-message, .seopress-user-consent-backdrop').forEach(function(element) {
            element.classList.add('seopress-user-consent-hide');
        });
        Cookies.remove('seopress-user-consent-close');
        Cookies.set('seopress-user-consent-accept', '1', { expires: Number(seopressAjaxGAUserConsent.seopress_cookies_expiration_days) });

        seopressNotifyConsent('accept');

        fetch(seopressAjaxGAUserConsent.seopress_cookies_user_consent, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'seopress_cookies_user_consent',
                consent: 'update',
                _ajax_nonce: seopressAjaxGAUserConsent.seopress_nonce,
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.data) {
                // Helper function to execute scripts properly
                const executeScript = (scriptContent, targetElement) => {
                    if (!scriptContent) return;
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = scriptContent;
                    const scripts = tempDiv.querySelectorAll('script');
                    scripts.forEach(oldScript => {
                        const newScript = document.createElement('script');
                        Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
                        newScript.textContent = oldScript.textContent;
                        targetElement.appendChild(newScript);
                    });
                    // Also add any non-script content
                    const nonScriptNodes = Array.from(tempDiv.childNodes).filter(node => node.nodeName !== 'SCRIPT');
                    nonScriptNodes.forEach(node => targetElement.appendChild(node.cloneNode(true)));
                };

                const head = document.head;
                const body = document.body;

                if (data.data.gtag_js) executeScript(data.data.gtag_js, head);
                if (data.data.matomo_js) executeScript(data.data.matomo_js, head);
                if (data.data.clarity_js) executeScript(data.data.clarity_js, head);
                if (data.data.custom) executeScript(data.data.custom, head);
                if (data.data.head_js) executeScript(data.data.head_js, head);
                if (data.data.body_js) executeScript(data.data.body_js, body);
                if (data.data.matomo_body_js) executeScript(data.data.matomo_body_js, body);
                if (data.data.footer_js) executeScript(data.data.footer_js, body);
            }
        })
        .catch(error => {
            console.error('Error:', error);
	});
    });
    
	const seopressUserConsentCloseBtn = document.getElementById('seopress-user-consent-close');
	if (seopressUserConsentCloseBtn) seopressUserConsentCloseBtn.addEventListener('click', function () {
        document.querySelectorAll('.seopress-user-consent.seopress-user-message, .seopress-user-consent-backdrop').forEach(function(element) {
            element.classList.add('seopress-user-consent-hide');
        });

        Cookies.remove('seopress-user-consent-accept');
        Cookies.set('seopress-user-consent-close', '1', { expires: Number(seopressAjaxGAUserConsent.seopress_cookies_expiration_days) });

        seopressNotifyConsent('decline');

        fetch(seopressAjaxGAUserConsent.seopress_cookies_user_consent, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'seopress_cookies_user_consent_close',
                consent: 'update',
                _ajax_nonce: seopressAjaxGAUserConsent.seopress_nonce,
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.data) {
                // Helper function to execute scripts properly
                const executeScript = (scriptContent, targetElement) => {
                    if (!scriptContent) return;
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = scriptContent;
                    const scripts = tempDiv.querySelectorAll('script');
                    scripts.forEach(oldScript => {
                        const newScript = document.createElement('script');
                        Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
                        newScript.textContent = oldScript.textContent;
                        targetElement.appendChild(newScript);
                    });
                    // Also add any non-script content
                    const nonScriptNodes = Array.from(tempDiv.childNodes).filter(node => node.nodeName !== 'SCRIPT');
                    nonScriptNodes.forEach(node => targetElement.appendChild(node.cloneNode(true)));
                };

                const head = document.head;
                if (data.data.gtag_consent_js) executeScript(data.data.gtag_consent_js, head);
                if (data.data.clarity_consent_js) executeScript(data.data.clarity_consent_js, head);
            }
        })
        .catch(error => {
            console.error('Error:', error);
	});
    });
    
	const seopressUserConsentEditBtn = document.getElementById('seopress-user-consent-edit');
	if (seopressUserConsentEditBtn) seopressUserConsentEditBtn.addEventListener('click', function () {
        document.querySelectorAll('.seopress-user-consent.seopress-user-message, .seopress-user-consent-backdrop').forEach(function(element) {
            element.classList.remove('seopress-user-consent-hide');
        });
	});
});
