document.addEventListener('DOMContentLoaded', function () {
    const banner = document.getElementById('happyfenceng-privacy-banner');
    const modal = document.getElementById('happyfenceng-privacy-modal');
    const manageLink = document.getElementById('happyfenceng-privacy-manage-link');

    const btnAccept = banner?.querySelector('.happyfenceng-privacy-btn.accept');
    const btnNecessary = banner?.querySelector('.happyfenceng-privacy-btn.necessary');
    const btnSettings = banner?.querySelector('.happyfenceng-privacy-btn.settings');

    const btnSave = modal?.querySelector('.happyfenceng-privacy-btn.save');
    const btnCancel = modal?.querySelectorAll('.happyfenceng-privacy-btn.cancel');


    // Rimuovi banner se consenso già dato
    if (localStorage.getItem('happyfenceng-privacy-consent')) {
        banner?.remove();
    }

    // Accetta tutti
    btnAccept?.addEventListener('click', function () {
        const consent = { necessary: true, analytics: true, marketing: true };
        localStorage.setItem('happyfenceng-privacy-consent', JSON.stringify(consent));
        banner?.remove();
        applyConsent(consent);
    });

    // Solo necessari
    btnNecessary?.addEventListener('click', function () {
        const consent = { necessary: true, analytics: false, marketing: false };
        localStorage.setItem('happyfenceng-privacy-consent', JSON.stringify(consent));
        banner?.remove();
        applyConsent(consent);
    });

    // Apri modal impostazioni
    btnSettings?.addEventListener('click', function () {
        modal.style.display = 'block';
    });

    // Link "gestisci preferenze"
    manageLink?.querySelector('a')?.addEventListener('click', function (e) {
        e.preventDefault();
        modal.style.display = 'block';
    });

    // Pulsanti "Annulla"
    btnCancel?.forEach(btn => btn.addEventListener('click', function () {
        modal.style.display = 'none';
    }));

    // Pulsante "Salva preferenze"
    btnSave?.addEventListener('click', function () {
        const consent = {
            necessary: true,
            analytics: modal.querySelector('input[name="analytics"]')?.checked || false,
            marketing: modal.querySelector('input[name="marketing"]')?.checked || false
        };
        localStorage.setItem('happyfenceng-privacy-consent', JSON.stringify(consent));
        modal.style.display = 'none';
        banner?.remove();
        applyConsent(consent);
    });

    // Funzione applicazione consenso
    function applyConsent(consent) {
        try {
            if (!consent.analytics) {
                document.querySelectorAll('script[data-happyfenceng-privacy="analytics"]').forEach(el => el.remove());
            }
            if (!consent.marketing) {
                document.querySelectorAll('script[data-happyfenceng-privacy="marketing"]').forEach(el => el.remove());
            }
        } catch (e) {
            console.warn('Error applying cookie preferences:', e);
        }
    }

    /* ---------- PRIVACY POLICY MODAL ---------- */
    const policyLink = document.getElementById('happyfenceng-privacy-policy-trigger');
    const policyModal = document.getElementById('happyfenceng-privacy-policy-modal');
    const policyClose = document.getElementById('happyprivacy-privacy-policy-modal-close');
    const policyContent = document.getElementById('happyprivacy-privacy-policy-modal-content-body');

    if (policyLink && policyModal && policyClose && policyContent) {
        policyLink.addEventListener('click', function (e) {
            e.preventDefault();
            fetch('/wp-json/happyfenceng-privacy/v1/policy')
                .then(res => res.text())
                .then(html => {
                    policyContent.innerHTML = html;
                    policyModal.style.display = 'block';
                })
                .catch(() => {
                    policyContent.innerHTML = '<p>Error loading policy.</p>';
                    policyModal.style.display = 'block';
                });
        });

        policyClose.addEventListener('click', function () {
            policyModal.style.display = 'none';
        });

        window.addEventListener('click', function (e) {
            if (e.target === policyModal) policyModal.style.display = 'none';
        });
    }

    /* ---------- COOKIE POLICY MODAL ---------- */
    const cookieLink = document.getElementById('happyfenceng-privacy-cookie-trigger');
    const cookieModal = document.getElementById('happyfenceng-privacy-cookie-modal');
    const cookieClose = document.getElementById('happyprivacy-privacy-cookie-modal-close');
    const cookieContent = document.getElementById('happyprivacy-privacy-cookie-modal-content-body');

    if (cookieLink && cookieModal && cookieClose && cookieContent) {
        cookieLink.addEventListener('click', function (e) {
            e.preventDefault();
            fetch('/wp-json/happyfenceng-privacy/v1/cookie')
                .then(res => res.text())
                .then(html => {
                    cookieContent.innerHTML = html;
                    cookieModal.style.display = 'block';
                })
                .catch(() => {
                    cookieContent.innerHTML = '<p>Error loading policy.</p>';
                    cookieModal.style.display = 'block';
                });
        });

        cookieClose.addEventListener('click', function () {
            cookieModal.style.display = 'none';
        });

        window.addEventListener('click', function (e) {
            if (e.target === cookieModal) cookieModal.style.display = 'none';
        });
    }

    /* ---------- TERMS MODAL ---------- */
    const termsLink = document.getElementById('happyfenceng-privacy-terms-trigger');
    const termsModal = document.getElementById('happyfenceng-privacy-terms-modal');
    const termsClose = document.getElementById('happyprivacy-privacy-terms-modal-close');
    const termsContent = document.getElementById('happyprivacy-privacy-terms-modal-content-body');

    if (termsLink && termsModal && termsClose && termsContent) {
        termsLink.addEventListener('click', function (e) {
            e.preventDefault();
            fetch('/wp-json/happyfenceng-privacy/v1/terms')
                .then(res => res.text())
                .then(html => {
                    termsContent.innerHTML = html;
                    termsModal.style.display = 'block';
                })
                .catch(() => {
                    termsContent.innerHTML = '<p>Error loading terms.</p>';
                    termsModal.style.display = 'block';
                });
        });

        termsClose.addEventListener('click', function () {
            termsModal.style.display = 'none';
        });

        window.addEventListener('click', function (e) {
            if (e.target === termsModal) termsModal.style.display = 'none';
        });
    }

    /* ---------- APPLICA CONSENSO GIÀ SALVATO ---------- */
    try {
        const existing = JSON.parse(localStorage.getItem('happyfenceng-privacy-consent') || '{}');
        if (Object.keys(existing).length > 0) {
            applyConsent(existing);
        }
    } catch (e) {
        console.warn('Error reading saved cookie preferences:', e);
    }
});
