(function ($) {
    $(document).on("consentUpdated.ctUltimateGdpr", function (event, level, level_ids) {
        let consent = {};

        function applyConsent1(level) {
            switch (level) {
                case '2':
                    consent.necessary = true;
                    break;
                case '3':
                    consent.necessary = true;
                    consent.functional = true;
                    break;
                case '4':
                    consent.necessary = true;
                    consent.functional = true;
                    consent.analytics = true;
                    break;
                case '5':
                    consent.necessary = true;
                    consent.functional = true;
                    consent.analytics = true;
                    consent.marketing = true;
                    break;
            }
        }

        function applyConsent2(level) {
            // Block each cookie group individually
            switch (level) {
                case '5':
                    consent.necessary = true;
                    break;
                case '6':
                    consent.functional = true;
                    break;
                case '7':
                    consent.analytics = true;
                    break;
                case '8':
                    consent.marketing = true;
                    break;
            }
        }

        function ctSetGConsentMode(consent) {
            // Define consent mode states based on user consent
            const consentModeStates = {
                'ad_storage': consent.marketing ? 'granted' : 'denied',
                'analytics_storage': consent.analytics ? 'granted' : 'denied',
                'functionality_storage': consent.functional ? 'granted' : 'denied',
                'personalization_storage': consent.functional ? 'granted' : 'denied',
                'security_storage': consent.necessary ? 'granted' : 'denied',
                'ad_user_data': consent.marketing ? 'granted' : 'denied',
                'ad_personalization': consent.marketing ? 'granted' : 'denied'
            };

            if (typeof gtag === 'function') {
                // Fallback to using gtag for consent update if GTM API is not available
                gtag('consent', 'update', consentModeStates);
            }

            // Store consent mode in localStorage for persistence
            localStorage.setItem('consentMode', JSON.stringify(consentModeStates));
        }

        if (level) {
            applyConsent1(level);
        }

        // If level_ids array is provided, iterate through each id and apply consent
        if (level_ids) {
            level_ids.forEach(function (level_id) {
                applyConsent2(level_id);
            });
        }

        ctSetGConsentMode(consent);
    });
})(jQuery);
