const data = window._wccGCMConfig;
let setDefaultSetting = true;
const regionSettings = data._regions || [];
const waitForTime = data.wait_for_update;
const wcc_bypass = !!data._wccBypass;
const wcc_gcm_debug = !!data._debugMode;
const is_gtm_template = !!data._isGTMTemplate;

window.dataLayer = window.dataLayer || [];
function gtag() {
    dataLayer.push(arguments);
}

function setConsentInitStates(consentData) {
    if (waitForTime > 0) consentData.wait_for_update = waitForTime;
    gtag("consent", "default", consentData );
}
if (!is_gtm_template) {
    gtag("set", "developer_id.dZDk4Nz", true);
}

if('advanced' === data._mode && !is_gtm_template) {
    gtag("set", "url_passthrough", !!data._urlPassthrough);
}
if(!is_gtm_template) {
    if( regionSettings.length ) {
        for (let index = 0; index < regionSettings.length; index++) {
            const regionSetting = regionSettings[index];
            // Helper function to convert "Allowed" to "granted" and "Denied" to "denied"
            const convertConsent = (value) => {
                if ("Allowed" === value || "Granted" === value) {
                    return "granted";
                } else if ("Denied" === value) {
                    return "denied";
                }
                return "denied"; // Default value if neither "Allowed" nor "Denied"
            };
        
            // Convert all relevant consent fields to "granted" or "denied"
            const consentRegionData = {
                ad_storage: convertConsent(regionSetting.ad_storage),
                analytics_storage: convertConsent(regionSetting.analytics_storage),
                functionality_storage: convertConsent(regionSetting.functionality_storage),
                personalization_storage: convertConsent(regionSetting.personalization_storage),
                security_storage: convertConsent(regionSetting.security_storage),
                ad_user_data: convertConsent(regionSetting.ad_user_data),
                ad_personalization: convertConsent(regionSetting.ad_personalization)
            };
        
            // Check if regionSetting.region is an array
            let regionsToSetFor = [];
            if (Array.isArray(regionSetting.region)) {
                regionsToSetFor = regionSetting.region.map((region) => region.trim());
            } else if (typeof regionSetting.region === 'string') {
                regionsToSetFor = regionSetting.region
                    .split(",")
                    .map((region) => region.trim())
                    .filter((region) => region);
            }
        
            if (regionsToSetFor.length > 0 && regionsToSetFor[0].toLowerCase() !== "all") {
                consentRegionData.region = regionsToSetFor;
            } else {
                setDefaultSetting = false;
                setDefaultConsents();
            }
        
            setConsentInitStates(consentRegionData);
        }
    } else {
        setDefaultConsents();
    }
}
function setDefaultConsents() {
    if(setDefaultSetting) {
        setConsentInitStates({
            ad_storage: "denied",
            analytics_storage: "denied",
            functionality_storage: "denied",
            personalization_storage: "denied",
            security_storage: "granted",
            ad_user_data: "denied",
            ad_personalization: "denied"
        });
    }
}
document.addEventListener("_wccBannerVisible", function(event) {
    let is_banner_visible = event.detail.bannerVisibility;
    let currentLaw = event.detail.currentLaw;
    // Declare categories variable
    let categories = {};
    if (!is_banner_visible || wcc_bypass ) {
        categories = {
            "accepted": [
                "necessary",
                "functional",
                "analytics",
                "performance",
                "advertisement",
                "others"
            ],
            "rejected": []
        };
    } else if (is_banner_visible) {
        // Initialize accepted and rejected arrays
        let accepted = ["necessary"];  // Assuming "necessary" is always accepted
        let rejected = [];

        // Categories to check
        let categoryList = ["functional", "analytics", "performance", "advertisement", "others"];

        // Check each category's cookie value
        categoryList.forEach(function(category) {
            let cookieValue = getCookieValue('wt_consent', category);
            if (cookieValue === 'yes') {
                accepted.push(category);
            } else if (cookieValue === 'no') {
                rejected.push(category);
            }
        });

        // Update the categories object based on cookie values
        categories = {
            "accepted": accepted,
            "rejected": rejected
        };
    }
    // If categories are defined and consent is already given, update the consent status
    if (categories && (isConsentGiven() || !is_banner_visible) || currentLaw === 'CCPA') {
        update_consent_status(categories, true);
    }
    if(wcc_gcm_debug && !is_gtm_template) {
        setConsentStatus();
    }
    
});

// Example usage with event listener
document.addEventListener("wcc_consent_update", function (eventData) {
    const categories = eventData.detail.categories;
    //Check whether categories exista nd consent already given
    if (categories && isConsentGiven()) {
        update_consent_status(categories);
        if(wcc_gcm_debug && !is_gtm_template) {
            setConsentStatus();
        }
    }
});

function update_consent_status(categories, is_refresh = false) {
    // Define category mappings between category names and storage variables
    const categoryMap = {
        'advertisement': 'wcc_ad_storage',
        'analytics': 'wcc_analytics_storage',
        'functional': 'wcc_functionality_storage'
    };

    // Initialize consent statuses to 'denied'
    Object.keys(categoryMap).forEach(category => {
        window[categoryMap[category]] = 'denied';  // Use window object to dynamically set variable
    });

    // Update consent statuses based on accepted categories
    categories.accepted.forEach(category => {
        if (categoryMap[category]) {
            window[categoryMap[category]] = 'granted';
        }
    });

    // Optionally check for a bypass (if needed)
    if (wcc_bypass) {
        Object.keys(categoryMap).forEach(category => {
            window[categoryMap[category]] = 'granted';
        });
        wcc_waiting_period = 100;
    }
    if( !is_refresh || !is_gtm_template ) {
        // Update consent in gtag
        gtag('consent', 'update', {
            'ad_storage': wcc_ad_storage,
            'ad_user_data': wcc_ad_storage,
            'ad_personalization': wcc_ad_storage,
            'analytics_storage': wcc_analytics_storage,
            'functionality_storage': wcc_functionality_storage,
            'personalization_storage': wcc_functionality_storage,
            'security_storage': "granted",
        });
    }
    if('advanced' === data._mode || is_gtm_template) {
        set_redact_data(wcc_ad_storage);
    }

    // Dispatch a custom event after consent mode updates are complete
    const consentUpdateEvent = new CustomEvent('wcc_gcm_updated', {
        detail: {
            ad_storage: wcc_ad_storage,
            analytics_storage: wcc_analytics_storage,
            functionality_storage: wcc_functionality_storage,
            personalization_storage: wcc_functionality_storage
        }
    });
    document.dispatchEvent(consentUpdateEvent);
    // Push consent data to dataLayer after consent mode updates are complete
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'wcc_gcm_consent_update',
        'ad_storage': wcc_ad_storage,
        'analytics_storage': wcc_analytics_storage,
        'functionality_storage': wcc_functionality_storage,
        'personalization_storage': wcc_functionality_storage
    });
}
function set_redact_data(wcc_ad_storage) {
    // Set ads redact data
    if (!!data._redactData) {
        let redactValue = wcc_ad_storage === 'granted' ? false : true;
        gtag("set", "ads_data_redaction", redactValue);
    }
}

function isConsentGiven() {
    let wcc_consent_exist = getCookieValue('wt_consent', 'action');
    // Return true if consent is 'yes' or 'no', otherwise return false
    return wcc_consent_exist === 'yes' || wcc_consent_exist === 'no';
}
function getCookieValue(name, key) {
    const cookies = document.cookie.split(';');
    for (const cookie of cookies) {
        const [cookieName, cookieValue] = cookie.split('=');
        if (cookieName.trim() === name) {
            const keyValuePairs = cookieValue.split(',');
            for (const pair of keyValuePairs) {
                const [pairKey, pairValue] = pair.split(':');
                if (pairKey.trim() === key) {
                    return pairValue.trim();
                }
            }
        }
    }
    return false; // Return 'false' if cookie doesn't exist or key is not found
}
function setConsentStatus() {
    function getConsentStatus(status) {
        if (status === undefined) return "missing";
        return status ? "granted" : "denied";
    }
    try {
        console.log("Debugging Google Consent Mode:\n");
        if (
            !window["google_tag_data"] ||
            !google_tag_data.ics ||
            !google_tag_data.ics.entries
        )
            return console.log("\n\tNo Consent Mode data found");
        let messageToPrint = "";
        const consentModeData = google_tag_data.ics.entries;
        let defaultMissing = false;
        for (const consentItem in consentModeData) {
            const currentItem = consentModeData[consentItem];
            const defaultValue = getConsentStatus(currentItem["default"]);
            const updatedValue = getConsentStatus(currentItem["update"]);
            messageToPrint = `${messageToPrint}\n\t${consentItem}:\n\t\tDefault: ${defaultValue}\n\t\tUpdate: ${updatedValue}\n\n`;
            if (defaultValue === "missing") defaultMissing = true;
        }
        if (defaultMissing) {
            messageToPrint += "%c\n\tWarning: Some categories are missing a default value.\n";
        }
        if (google_tag_data.ics.wasSetLate) {
            messageToPrint += "%c\n\tWarning: A tag read consent before a default was set.\n";
        } else {
            messageToPrint += "%c\n\tConsent mode states were set correctly.";
        }

        if (defaultMissing || google_tag_data.ics.wasSetLate) {
            console.log(messageToPrint, "color: #C00");
        } else {
            console.log(messageToPrint, "color: #0C0");
        }
    } catch (error) {
        return console.log("\n\nWarning: Error detecting consent mode status");
    }
}