/**
 * Modern Cookie Consent Banner
 * GDPR & CCPA Compliant
 */

class CookieConsent {
    constructor(options = {}) {
        this.options = {
            cookieName: 'cookie_consent',
            expiryDays: 365,
            privacyUrl: options.privacyUrl || '/privacy-policy',
            ...options
        };
        
        this.init();
    }
    
    init() {
        // Check if consent already given
        if (this.hasConsent()) {
            this.applyConsent();
            return;
        }
        
        // Show banner after short delay
        setTimeout(() => {
            this.showBanner();
        }, 1000);
    }
    
    hasConsent() {
        return this.getCookie(this.options.cookieName) !== null;
    }
    
    showBanner() {
        const banner = this.createBanner();
        document.body.appendChild(banner);
        
        // Trigger animation
        setTimeout(() => {
            banner.classList.add('show');
        }, 100);
    }
    
    createBanner() {
        const banner = document.createElement('div');
        banner.className = 'cookie-consent-banner';
        banner.id = 'cookieConsentBanner';
        
        banner.innerHTML = `
            <div class="cookie-consent-container">
                <div class="cookie-consent-icon">🍪</div>
                <div class="cookie-consent-content">
                    <h4 class="cookie-consent-title">We Value Your Privacy</h4>
                    <p class="cookie-consent-text">
                        We use cookies to enhance your browsing experience, serve personalized content, and analyze our traffic. 
                        By clicking "Accept All", you consent to our use of cookies. 
                        <a href="${this.options.privacyUrl}" target="_blank">Learn more</a>
                    </p>
                </div>
                <div class="cookie-consent-actions">
                    <button class="cookie-consent-button cookie-consent-settings" onclick="cookieConsent.showSettings()">
                        Settings
                    </button>
                    <button class="cookie-consent-button cookie-consent-decline" onclick="cookieConsent.decline()">
                        Decline
                    </button>
                    <button class="cookie-consent-button cookie-consent-accept" onclick="cookieConsent.acceptAll()">
                        Accept All
                    </button>
                </div>
            </div>
        `;
        
        return banner;
    }
    
    createSettingsModal() {
        const modal = document.createElement('div');
        modal.className = 'cookie-settings-modal';
        modal.id = 'cookieSettingsModal';
        
        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>
                <div class="cookie-settings-body">
                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4 class="cookie-category-title">Essential Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" checked disabled>
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies are necessary for the website to function and cannot be switched off. 
                            They are usually only set in response to actions made by you such as setting your privacy preferences, 
                            logging in or filling in forms.
                        </p>
                    </div>
                    
                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4 class="cookie-category-title">Analytics Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="analyticsToggle" checked>
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies allow us to count visits and traffic sources so we can measure and improve 
                            the performance of our site. They help us know which pages are the most and least popular 
                            and see how visitors move around the site.
                        </p>
                    </div>
                    
                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4 class="cookie-category-title">Marketing Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="marketingToggle" checked>
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies may be set through our site by our advertising partners. They may be used 
                            to build a profile of your interests and show you relevant ads on other sites. They work 
                            by uniquely identifying your browser and device.
                        </p>
                    </div>
                    
                    <div class="cookie-category">
                        <div class="cookie-category-header">
                            <h4 class="cookie-category-title">Functional Cookies</h4>
                            <label class="cookie-toggle">
                                <input type="checkbox" id="functionalToggle" checked>
                                <span class="cookie-toggle-slider"></span>
                            </label>
                        </div>
                        <p class="cookie-category-description">
                            These cookies enable the website to provide enhanced functionality and personalization. 
                            They may be set by us or by third party providers whose services we have added to our pages.
                        </p>
                    </div>
                </div>
                <div class="cookie-settings-footer">
                    <button class="cookie-settings-save" onclick="cookieConsent.saveSettings()">
                        Save Preferences
                    </button>
                </div>
            </div>
        `;
        
        // Close on overlay click
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.hideSettings();
            }
        });
        
        return modal;
    }
    
    showSettings() {
        let modal = document.getElementById('cookieSettingsModal');
        if (!modal) {
            modal = this.createSettingsModal();
            document.body.appendChild(modal);
        }
        modal.classList.add('show');
    }
    
    hideSettings() {
        const modal = document.getElementById('cookieSettingsModal');
        if (modal) {
            modal.classList.remove('show');
        }
    }
    
    acceptAll() {
        const consent = {
            essential: true,
            analytics: true,
            marketing: true,
            functional: true,
            timestamp: new Date().toISOString()
        };
        
        this.saveConsent(consent);
        this.hideBanner();
        this.applyConsent();
    }
    
    decline() {
        const consent = {
            essential: true,
            analytics: false,
            marketing: false,
            functional: false,
            timestamp: new Date().toISOString()
        };
        
        this.saveConsent(consent);
        this.hideBanner();
        this.applyConsent();
    }
    
    saveSettings() {
        const consent = {
            essential: true,
            analytics: document.getElementById('analyticsToggle').checked,
            marketing: document.getElementById('marketingToggle').checked,
            functional: document.getElementById('functionalToggle').checked,
            timestamp: new Date().toISOString()
        };
        
        this.saveConsent(consent);
        this.hideSettings();
        this.hideBanner();
        this.applyConsent();
    }
    
    saveConsent(consent) {
        this.setCookie(this.options.cookieName, JSON.stringify(consent), this.options.expiryDays);
    }
    
    getConsent() {
        const cookie = this.getCookie(this.options.cookieName);
        return cookie ? JSON.parse(cookie) : null;
    }
    
    applyConsent() {
        const consent = this.getConsent();
        if (!consent) return;
        
        // Apply consent preferences
        if (consent.analytics) {
            this.enableAnalytics();
        }
        
        if (consent.marketing) {
            this.enableMarketing();
        }
        
        if (consent.functional) {
            this.enableFunctional();
        }
    }
    
    enableAnalytics() {
        // Enable Google Analytics, etc.
    }
    
    enableMarketing() {
        // Enable marketing cookies
    }
    
    enableFunctional() {
        // Enable functional cookies
    }
    
    hideBanner() {
        const banner = document.getElementById('cookieConsentBanner');
        if (banner) {
            banner.classList.remove('show');
            setTimeout(() => {
                banner.remove();
            }, 400);
        }
    }
    
    setCookie(name, value, days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = name + "=" + value + ";" + expires + ";path=/;SameSite=Lax";
    }
    
    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 revoke consent
    revokeConsent() {
        document.cookie = this.options.cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        location.reload();
    }
}

// Initialize on page load
let cookieConsent;
document.addEventListener('DOMContentLoaded', () => {
    cookieConsent = new CookieConsent({
        privacyUrl: '/privacy-policy' // Update this to your privacy policy URL
    });
});
