// Handle banner visibility event
document.addEventListener("_wccBannerVisible", function(event) {
    const is_banner_visible = event.detail.bannerVisibility;
    const mcmConfig = window._wccMCMConfig;
    const consentData = getWccConsent();
    const categories = consentData.categories;
    const currentLaw = consentData.currentLaw;
    
    handleClarity(mcmConfig.clarity, is_banner_visible, categories);
    handleUET(mcmConfig.uet, is_banner_visible, categories, currentLaw, true);
});

// Existing consent update event listener
document.addEventListener("wcc_consent_update", function () {
    const mcmConfig = window._wccMCMConfig;
    const consentData = getWccConsent();
    const categories = consentData.categories;
    
    if (categories && isConsentGiven()) {
        handleClarity(mcmConfig.clarity, true, categories);
        handleUET(mcmConfig.uet, true, categories, consentData.currentLaw, false);
    }
});

function handleClarity(clarity, is_banner_visible, categories) {
    if (clarity && window.clarity) {
        // Use the new consentv2 API format
        const consentData = {
            ad_Storage: categories.advertisement === true ? "granted" : "denied",
            analytics_Storage: categories.analytics === true ? "granted" : "denied"
        };
        
        // If banner is not visible, assume all consent is granted
        if (!is_banner_visible) {
            consentData.ad_Storage = "granted";
            consentData.analytics_Storage = "granted";
        }
        
        // If both analytics and advertisement are denied, clear Clarity cookies and start new session
        if (consentData.ad_Storage === "denied" && consentData.analytics_Storage === "denied") {
            window.clarity('consent', false);
        } else {
            window.clarity('consentv2', consentData);
        }
    }
}

function handleUET(uet, is_banner_visible, categories, currentLaw, sendDefault = true) {
    if (uet && window.uetq) {
        if (sendDefault) {
            window.uetq.push('consent', 'default', {
                'ad_storage': 'denied'
            });
        }
        
        if (!is_banner_visible || currentLaw === 'ccpa' || isConsentGiven()) {
            window.uetq.push('consent', 'update', {
                'ad_storage': categories.advertisement === true ? 'granted' : 'denied'
            });
            if (!categories.advertisement) {
                // Delete UET tracking cookies
                const uetCookies = ['_uetsid', '_uetvid', '_uetmsclkid'];
                const hostname = document.location.hostname;
                const parentDomain = hostname.split('.').slice(-2).join('.');
                
                // Try with different domain variations
                const domains = [
                    '', // current domain
                    hostname, // full domain
                    '.' + hostname, // full domain with dot
                    parentDomain, // parent domain
                    '.' + parentDomain // parent domain with dot
                ];
                
                uetCookies.forEach(cookieId => {
                    domains.forEach(domain => {
                        window.webtoffee._wccSetCookie(cookieId, "", -1, domain);
                        // Also try direct cookie deletion
                        document.cookie = `${cookieId}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain}`;
                    });
                });

                // Clean up localStorage
                try {
                    ['_uetvid', '_uetvid_exp', '_uetsid', '_uetsid_exp'].forEach(key => {
                        localStorage.removeItem(key);
                    });
                } catch (e) {
                    console.log('LocalStorage access error:', e);
                }
            }
        }
    }
}

function isConsentGiven() {
    let wcc_consent_exist = getCookieValue('wt_consent', 'action');
    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;
}