function iccbGetPrefs() {
    try {
        return JSON.parse(localStorage.getItem('iccb_prefs_v1') || '{}');
    } catch (error) {
        return {};
    }
}

function iccbSetPrefs(preferences) {
    localStorage.setItem('iccb_prefs_v1', JSON.stringify(preferences));
}

function iccbGetDisplayPrefs() {
    const saved = iccbGetPrefs();
    if (saved && saved.__consented === true) {
        return saved;
    }

    const defaults = {};
    ['necessary', 'functional', 'analytics', 'performance', 'marketing', 'uncategorized'].forEach((category) => {
        defaults[category] = false;
    });

    (window.ICCB_CONFIG.default_categories || []).forEach((category) => {
        defaults[category] = true;
    });
    defaults.necessary = true;

    return defaults;
}

function iccbSyncBannerTogglesFromPrefs() {
    const prefs = iccbGetDisplayPrefs();
    document.querySelectorAll('#iccb-banner-accordion input[type="checkbox"][data-category]').forEach((input) => {
        input.checked = Boolean(prefs[input.dataset.category]);
    });
}

function iccbLogConsentToServer(preferences, userId = null) {
    fetch(window.ICCB_CONFIG.ajax_url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'iccb_log_consent',
            consent: JSON.stringify(preferences),
            user_id: userId,
            domain: window.location.hostname
        })
    }).catch(() => {});
}

function iccbPushConsentUpdateFromPrefs(preferences) {
    if (typeof gtag !== 'function') {
        return;
    }

    const state = (allowed) => allowed ? 'granted' : 'denied';
    gtag('consent', 'update', {
        analytics_storage: state(preferences.analytics),
        ad_storage: state(preferences.marketing),
        ad_user_data: state(preferences.marketing),
        ad_personalization: state(preferences.marketing),
        functionality_storage: state(preferences.functional),
        security_storage: 'granted'
    });
}

function iccbInjectFacebookPixel(pixelId) {
    if (!pixelId || window.fbq) {
        return;
    }

    (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 = true;
        n.version = '2.0';
        n.queue = [];
        t = b.createElement(e);
        t.async = true;
        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', pixelId);
    fbq('track', 'PageView');
}

function iccbInjectLinkedInPixel(partnerId) {
    if (!partnerId || window._iccbLinkedInLoaded) {
        return;
    }

    window._iccbLinkedInLoaded = true;
    const config = document.createElement('script');
    config.text = `_linkedin_partner_id="${partnerId}";window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push("${partnerId}");`;
    document.head.appendChild(config);

    const script = document.createElement('script');
    script.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js';
    script.async = true;
    document.head.appendChild(script);
}

function iccbInjectTrackingByConsent(preferences) {
    const settings = window.ICCB_CONFIG.pixel_settings || {};
    iccbPushConsentUpdateFromPrefs(preferences);

    if (settings.mode === 'gtm_plus_pixels' && preferences.marketing) {
        if (settings.facebook) {
            iccbInjectFacebookPixel(settings.facebook);
        }
        if (settings.linkedin) {
            iccbInjectLinkedInPixel(settings.linkedin);
        }
    }
}

function iccbHandleConsent(preferences) {
    preferences.necessary = true;
    preferences.__consented = true;
    preferences.__ts = Date.now();
    iccbSetPrefs(preferences);
    iccbLogConsentToServer(preferences, window.ICCB_CONFIG.user_id);
    iccbInjectTrackingByConsent(preferences);
    iccbSyncBannerTogglesFromPrefs();
    iccbHideBanner();
    window.dispatchEvent(new CustomEvent('iccb:prefs-updated', { detail: preferences }));
}

function iccbShowBanner() {
    const banner = document.getElementById('iccb-cookie-banner');
    const revoke = document.getElementById('iccb-revoke');
    if (banner) {
        banner.classList.remove('iccb-hidden');
        revoke?.classList.add('iccb-hidden');
    }
}

function iccbHideBanner() {
    const banner = document.getElementById('iccb-cookie-banner');
    const overlay = document.getElementById('iccb-overlay');
    const revoke = document.getElementById('iccb-revoke');
    if (banner) {
        banner.classList.add('iccb-hidden');
        revoke?.classList.remove('iccb-hidden');
        overlay?.classList.remove('is-visible');
        document.body.classList.remove('iccb-locked');
    }
}

function iccbShowBannerOrRevoke() {
    const prefs = iccbGetPrefs();
    if (!prefs || prefs.__consented !== true) {
        iccbShowBanner();
        iccbSyncBannerTogglesFromPrefs();
        return;
    }

    document.getElementById('iccb-revoke')?.classList.remove('iccb-hidden');
    iccbInjectTrackingByConsent(prefs);
}

document.addEventListener('DOMContentLoaded', () => {
    const banner = document.getElementById('iccb-cookie-banner');
    new IccbBanner({
        cookieUrl: window.ICCB_CONFIG.cookie_json_url,
        accordionId: 'iccb-banner-accordion',
        storageKey: 'iccb_prefs_v1'
    }).init().then(iccbSyncBannerTogglesFromPrefs);

    document.getElementById('iccb-accept-all')?.addEventListener('click', () => {
        iccbHandleConsent({ necessary: true, analytics: true, marketing: true, functional: true, performance: true, uncategorized: true });
    });
    document.getElementById('iccb-reject-all')?.addEventListener('click', () => {
        iccbHandleConsent({ necessary: true, analytics: false, marketing: false, functional: false, performance: false, uncategorized: false });
    });
    document.getElementById('iccb-save-preferences')?.addEventListener('click', () => {
        iccbHandleConsent(iccbGetPrefs());
        banner?.classList.remove('open');
    });
    document.getElementById('iccb-manage-preferences')?.addEventListener('click', (event) => {
        event.preventDefault();
        banner?.classList.toggle('open');
        if (banner?.classList.contains('open')) {
            iccbSyncBannerTogglesFromPrefs();
        }
    });
    document.getElementById('iccb-revoke')?.addEventListener('click', () => {
        iccbShowBanner();
        iccbSyncBannerTogglesFromPrefs();
    });
    window.addEventListener('iccb:prefs-updated', iccbSyncBannerTogglesFromPrefs);
    iccbShowBannerOrRevoke();
});
