/**
 * Cookie Consent Manager
 * Handles cookie consent banner and user preferences
 */

(function() {
    'use strict';

    // Configuration
    const COOKIE_CONFIG = {
        consentCookieName: 'omega_cookie_consent',
        preferencesCookieName: 'omega_cookie_preferences',
        expirationDays: 365, 
        bannerDelay: 1000 
    };

    // Default cookie preferences
    const DEFAULT_PREFERENCES = {
        essential: true,     // Always true, cannot be disabled
        functional: false,
        analytics: false,
        marketing: false
    };

    // Cookie Consent Manager Class
    class CookieConsentManager {
        constructor() {
            this.preferences = DEFAULT_PREFERENCES;
            this.bannerElement = null;
            this.modalElement = null;
            this.initialized = false;
            this.init();
        }

        init() {
            // Prevent multiple initializations
            if (this.initialized) {
                console.log('Cookie consent already initialized, skipping...');
                return;
            }
            
            this.initialized = true;
            
            // Debug: Log cookie status
            console.log('Cookie Consent Debug:', {
                consentCookie: this.getCookie(COOKIE_CONFIG.consentCookieName),
                preferencesCookie: this.getCookie(COOKIE_CONFIG.preferencesCookieName),
                allCookies: document.cookie
            });

            // Check if consent has already been given
            if (this.hasConsent()) {
                console.log('Cookie consent already given, loading preferences...');
                this.loadPreferences();
                return;
            }

            console.log('No cookie consent found, showing banner...');
            
            // Create and show the cookie banner
            this.createBanner();
            this.createModal();
            
            // Show banner after delay
            setTimeout(() => {
                this.showBanner();
            }, COOKIE_CONFIG.bannerDelay);
        }

        hasConsent() {
            return this.getCookie(COOKIE_CONFIG.consentCookieName) !== null;
        }

        loadPreferences() {
            const savedPreferences = this.getCookie(COOKIE_CONFIG.preferencesCookieName);
            if (savedPreferences) {
                try {
                    this.preferences = JSON.parse(savedPreferences);
                } catch (e) {
                    console.warn('Failed to parse cookie preferences:', e);
                    this.preferences = DEFAULT_PREFERENCES;
                }
            }
        }

        createBanner() {
            const banner = document.createElement('div');
            banner.className = 'cookie-consent-banner';
            banner.innerHTML = `
                <div class="cookie-consent-content">
                    <div class="cookie-consent-text">
                        <p>
                            We use cookies to enhance your browsing experience, analyze site traffic, and personalize content. 
                            By clicking "Accept All", you consent to our use of cookies. 
                            <a href="cookie-policy.html" target="_blank">Learn more</a> about our cookie policy.
                        </p>
                    </div>
                    <div class="cookie-consent-actions">
                        <button class="cookie-btn cookie-btn-settings" onclick="cookieConsent.showSettings()">
                            Customize
                        </button>
                        <button class="cookie-btn cookie-btn-decline" onclick="cookieConsent.declineAll()">
                            Decline All
                        </button>
                        <button class="cookie-btn cookie-btn-accept" onclick="cookieConsent.acceptAll()">
                            Accept All
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(banner);
            this.bannerElement = banner;
        }

        createModal() {
            const modal = document.createElement('div');
            modal.className = 'cookie-settings-modal';
            modal.innerHTML = `
                <div class="cookie-settings-content">
                    <div class="cookie-settings-header">
                        <h3>Cookie Settings</h3>
                        <button class="cookie-settings-close" onclick="cookieConsent.hideSettings()">
                            ×
                        </button>
                    </div>
                    
                    <p style="margin-bottom: 25px; color: var(--text-color);">
                        Customize your cookie preferences below. You can change your settings at any time.
                    </p>

                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4>Essential Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="essential-toggle" checked disabled>
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies are necessary for the website to function properly. They enable basic features like page navigation and access to secure areas.
                        </p>
                    </div>

                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4>Functional Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="functional-toggle">
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies enhance functionality and personalization, such as remembering your preferences and settings.
                        </p>
                    </div>

                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4>Analytics Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="analytics-toggle">
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies help us understand how visitors interact with our website by collecting and reporting information anonymously.
                        </p>
                    </div>

                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4>Marketing Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="marketing-toggle">
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies are used to track visitors across websites to display relevant advertisements and marketing content.
                        </p>
                    </div>

                    <div class="cookie-settings-actions">
                        <button class="cookie-btn cookie-btn-decline" onclick="cookieConsent.saveSettings(false)">
                            Save & Decline All
                        </button>
                        <button class="cookie-btn cookie-btn-accept" onclick="cookieConsent.saveSettings(true)">
                            Save Settings
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            this.modalElement = modal;

            // Close modal when clicking outside
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.hideSettings();
                }
            });
        }

        showBanner() {
            if (this.bannerElement) {
                this.bannerElement.classList.add('show');
            }
        }

        hideBanner() {
            if (this.bannerElement) {
                this.bannerElement.classList.remove('show');
                setTimeout(() => {
                    if (this.bannerElement && this.bannerElement.parentNode) {
                        this.bannerElement.parentNode.removeChild(this.bannerElement);
                    }
                }, 300);
            }
        }

        showSettings() {
            if (this.modalElement) {
                // Load current preferences into toggles
                document.getElementById('functional-toggle').checked = this.preferences.functional;
                document.getElementById('analytics-toggle').checked = this.preferences.analytics;
                document.getElementById('marketing-toggle').checked = this.preferences.marketing;
                
                this.modalElement.classList.add('show');
            }
        }

        hideSettings() {
            if (this.modalElement) {
                this.modalElement.classList.remove('show');
            }
        }

        acceptAll() {
            this.preferences = {
                essential: true,
                functional: true,
                analytics: true,
                marketing: true
            };
            this.saveConsent();
            this.hideBanner();
            this.hideSettings();
            
            // Initialize all tracking/analytics
            this.initializeTracking();
        }

        declineAll() {
            this.preferences = {
                essential: true,
                functional: false,
                analytics: false,
                marketing: false
            };
            this.saveConsent();
            this.hideBanner();
            this.hideSettings();
        }

        saveSettings(acceptMode = true) {
            if (acceptMode) {
                // Get preferences from toggles
                this.preferences = {
                    essential: true, // Always true
                    functional: document.getElementById('functional-toggle').checked,
                    analytics: document.getElementById('analytics-toggle').checked,
                    marketing: document.getElementById('marketing-toggle').checked
                };
            } else {
                // Decline all except essential
                this.preferences = {
                    essential: true,
                    functional: false,
                    analytics: false,
                    marketing: false
                };
            }
            
            this.saveConsent();
            this.hideBanner();
            this.hideSettings();
            
            if (acceptMode && (this.preferences.analytics || this.preferences.marketing)) {
                this.initializeTracking();
            }
        }

        saveConsent() {
            console.log('Saving cookie consent...', this.preferences);
            
            // Save consent status
            this.setCookie(COOKIE_CONFIG.consentCookieName, 'true', COOKIE_CONFIG.expirationDays);
            
            // Save preferences
            this.setCookie(COOKIE_CONFIG.preferencesCookieName, JSON.stringify(this.preferences), COOKIE_CONFIG.expirationDays);
            
            // Verify cookies were saved
            const consentSaved = this.getCookie(COOKIE_CONFIG.consentCookieName);
            const preferencesSaved = this.getCookie(COOKIE_CONFIG.preferencesCookieName);
            
            console.log('Cookie consent save verification:', {
                consent: consentSaved,
                preferences: preferencesSaved,
                success: !!(consentSaved && preferencesSaved)
            });
        }

        initializeTracking() {
            // Initialize Google Analytics if analytics cookies are accepted
            if (this.preferences.analytics) {
                this.loadGoogleAnalytics();
            }

            // Initialize other tracking services if marketing cookies are accepted
            if (this.preferences.marketing) {
                this.loadMarketingScripts();
            }
        }

        loadGoogleAnalytics() {
            // Add your Google Analytics tracking code here
            // This is a placeholder - replace with your actual GA tracking ID
            /*
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'GA_TRACKING_ID');
            
            const gaScript = document.createElement('script');
            gaScript.async = true;
            gaScript.src = 'https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID';
            document.head.appendChild(gaScript);
            */
            
            console.log('Analytics tracking initialized');
        }

        loadMarketingScripts() {
            // Add your marketing/advertising scripts here
            console.log('Marketing tracking initialized');
        }

        // Utility methods for cookie management
        setCookie(name, value, days) {
            const expires = new Date();
            expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
            
            // Detect if running locally
            const isLocal = window.location.protocol === 'file:' || 
                          window.location.hostname === 'localhost' || 
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname === '';
            
            let cookieString;
            
            if (isLocal) {
                // For local development - use minimal cookie settings
                cookieString = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/`;
                console.log('Local development detected - using basic cookie settings');
            } else {
                // For production - use full security settings
                cookieString = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
            }
            
            document.cookie = cookieString;
            console.log('Setting cookie:', cookieString);
            
            // Verify cookie was set
            const verification = this.getCookie(name);
            console.log('Cookie verification:', name, verification ? 'SUCCESS' : 'FAILED');
            
            // If cookie failed and we're local, try localStorage as fallback
            if (!verification && isLocal) {
                console.log('Cookie failed in local environment, trying localStorage fallback...');
                this.setLocalStorage(name, value, days);
            }
        }

        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) {
                    const value = c.substring(nameEQ.length, c.length);
                    try {
                        return decodeURIComponent(value);
                    } catch (e) {
                        return value;
                    }
                }
            }
            
            // Fallback to localStorage for local development
            const isLocal = window.location.protocol === 'file:' || 
                          window.location.hostname === 'localhost' || 
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname === '';
            
            if (isLocal) {
                const fallback = this.getLocalStorage(name);
                if (fallback) {
                    console.log('Using localStorage fallback for cookie:', name);
                    return fallback;
                }
            }
            
            return null;
        }

        // localStorage fallback methods for local development
        setLocalStorage(name, value, days) {
            try {
                const expires = new Date();
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                
                const data = {
                    value: value,
                    expires: expires.getTime()
                };
                
                localStorage.setItem(`cookie_fallback_${name}`, JSON.stringify(data));
                console.log('localStorage fallback set for:', name);
            } catch (e) {
                console.error('localStorage fallback failed:', e);
            }
        }

        getLocalStorage(name) {
            try {
                const item = localStorage.getItem(`cookie_fallback_${name}`);
                if (!item) return null;
                
                const data = JSON.parse(item);
                
                // Check if expired
                if (new Date().getTime() > data.expires) {
                    localStorage.removeItem(`cookie_fallback_${name}`);
                    return null;
                }
                
                return data.value;
            } catch (e) {
                console.error('localStorage fallback read failed:', e);
                return null;
            }
        }

        deleteLocalStorage(name) {
            try {
                localStorage.removeItem(`cookie_fallback_${name}`);
            } catch (e) {
                console.error('localStorage fallback delete failed:', e);
            }
        }

        deleteCookie(name) {
            document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/`;
            
            // Also clear localStorage fallback
            this.deleteLocalStorage(name);
        }

        // Public API methods
        getPreferences() {
            return { ...this.preferences };
        }

        updatePreferences(newPreferences) {
            this.preferences = { ...this.preferences, ...newPreferences };
            this.saveConsent();
        }

        resetConsent() {
            this.deleteCookie(COOKIE_CONFIG.consentCookieName);
            this.deleteCookie(COOKIE_CONFIG.preferencesCookieName);
            location.reload();
        }
    }

    // Initialize when DOM is ready
    function initializeCookieConsent() {
        // Prevent multiple instances
        if (window.cookieConsent) {
            console.log('Cookie consent already exists, skipping initialization...');
            return;
        }
        
        console.log('Initializing cookie consent...');
        window.cookieConsent = new CookieConsentManager();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeCookieConsent);
    } else {
        initializeCookieConsent();
    }

})();