// Cookie Consent Manager for QR Rapido
class CookieConsentManager {
    constructor() {
        this.CONSENT_COOKIE = 'qrrapido_cookie_consent';
        this.CONSENT_EXPIRY_DAYS = 365;
        this.banner = null;
        
        this.init();
    }

    init() {
        // Wait for DOM to be ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setup());
        } else {
            this.setup();
        }
    }

    setup() {
        this.banner = document.getElementById('cookie-consent-banner');
        if (!this.banner) {
            console.warn('Cookie consent banner not found');
            return;
        }

        // Check if user has already given consent
        if (!this.hasConsent()) {
            this.showBanner();
        }

        // Setup event listeners
        this.setupEventListeners();
    }

    setupEventListeners() {
        const acceptAllBtn = document.getElementById('cookie-accept-all');
        const acceptEssentialBtn = document.getElementById('cookie-accept-essential');

        if (acceptAllBtn) {
            acceptAllBtn.addEventListener('click', () => this.acceptAll());
        }

        if (acceptEssentialBtn) {
            acceptEssentialBtn.addEventListener('click', () => this.acceptEssential());
        }
    }

    hasConsent() {
        const consent = this.getCookie(this.CONSENT_COOKIE);
        return consent === 'all' || consent === 'essential';
    }

    acceptAll() {
        this.setConsent('all');
        this.enableAnalytics();
        this.hideBanner();
        
        console.log('✅ User accepted all cookies - Analytics enabled');
    }

    acceptEssential() {
        this.setConsent('essential');
        this.disableAnalytics();
        this.hideBanner();
        
        console.log('⚡ User accepted essential cookies only - Analytics disabled');
    }

    setConsent(type) {
        const expiryDate = new Date();
        expiryDate.setTime(expiryDate.getTime() + (this.CONSENT_EXPIRY_DAYS * 24 * 60 * 60 * 1000));
        
        document.cookie = `${this.CONSENT_COOKIE}=${type}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax`;
    }

    enableAnalytics() {
        // Enable Google Analytics if gtag is available
        if (typeof gtag !== 'undefined') {
            gtag('consent', 'update', {
                'analytics_storage': 'granted'
            });
        }

        // Enable other tracking if needed
        this.enableGoogleAnalytics();
    }

    disableAnalytics() {
        // Disable Google Analytics
        if (typeof gtag !== 'undefined') {
            gtag('consent', 'update', {
                'analytics_storage': 'denied'
            });
        }

        // Clear existing analytics cookies
        this.clearAnalyticsCookies();
    }

    enableGoogleAnalytics() {
        // Google Analytics is already loaded in _Layout.cshtml
        // This just ensures consent is properly granted
        if (typeof gtag !== 'undefined') {
            // Send a page view event to confirm analytics is working
            gtag('event', 'cookie_consent_granted', {
                'event_category': 'Cookie Consent',
                'event_label': 'Analytics Enabled'
            });
        }
    }

    clearAnalyticsCookies() {
        // Clear Google Analytics cookies
        const gaCookies = ['_ga', '_gid', '_gat', '_gtag_GA_MEASUREMENT_ID'];
        
        gaCookies.forEach(cookieName => {
            // Clear for current domain
            document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;`;
            
            // Clear for parent domain
            const domain = window.location.hostname.replace(/^www\./, '.');
            document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain};`;
        });

        console.log('🧹 Analytics cookies cleared');
    }

    showBanner() {
        if (this.banner) {
            this.banner.style.display = 'block';
            
            // Add body padding to prevent content overlap
            document.body.style.paddingBottom = this.banner.offsetHeight + 'px';
        }
    }

    hideBanner() {
        if (this.banner) {
            this.banner.classList.add('hidden');
            
            // Remove body padding
            document.body.style.paddingBottom = '0';
            
            setTimeout(() => {
                this.banner.style.display = 'none';
                this.banner.classList.remove('hidden');
            }, 300);
        }
    }

    getCookie(name) {
        const nameEQ = name + '=';
        const ca = document.cookie.split(';');
        
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        
        return null;
    }

    // Public method to check consent status
    getConsentStatus() {
        return this.getCookie(this.CONSENT_COOKIE);
    }

    // Public method to revoke consent (for privacy settings)
    revokeConsent() {
        document.cookie = `${this.CONSENT_COOKIE}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;`;
        this.clearAnalyticsCookies();
        this.showBanner();
    }
}

// Initialize cookie consent manager
const cookieConsent = new CookieConsentManager();

// Make it globally available for debugging/manual control
window.cookieConsent = cookieConsent;