// AUTO TESTER - Cookie Consent System

// Cookie Consent Configuration
const cookieConfig = {
    consentKey: 'autotester_cookie_consent',
    consentExpiry: 365, // days
    showDelay: 1000, // ms
    hideDelay: 300, // ms
    cookiePolicyUrl: '/privacy.html',
    privacyPolicyUrl: '/privacy.html'
};

// Cookie Consent HTML
function createCookieConsent() {
    const consentHtml = `
        <div id="cookieConsent" class="cookie-consent" role="dialog" aria-labelledby="cookieTitle" aria-describedby="cookieDescription">
            <div class="cookie-content">
                <div class="cookie-icon">
                    <i class="fas fa-cookie-bite"></i>
                </div>
                <div class="cookie-text">
                    <h3 id="cookieTitle">We Use Cookies</h3>
                    <p id="cookieDescription">
                        We use cookies to enhance your experience, analyze site traffic, and personalize content. 
                        By continuing to use our site, you agree to our 
                        <a href="${cookieConfig.privacyPolicyUrl}" target="_blank" rel="noopener">Privacy Policy</a>.
                    </p>
                </div>
                <div class="cookie-actions">
                    <button type="button" class="btn-cookie btn-accept" onclick="acceptCookies()">
                        <i class="fas fa-check"></i>
                        Accept All
                    </button>
                    <button type="button" class="btn-cookie btn-reject" onclick="rejectCookies()">
                        <i class="fas fa-times"></i>
                        Reject
                    </button>
                    <button type="button" class="btn-cookie btn-settings" onclick="showCookieSettings()">
                        <i class="fas fa-cog"></i>
                        Settings
                    </button>
                </div>
            </div>
        </div>
    `;
    
    // Add to page
    const container = document.createElement('div');
    container.innerHTML = consentHtml;
    document.body.appendChild(container.firstElementChild);
}

// Check if consent exists
function checkCookieConsent() {
    const consent = localStorage.getItem(cookieConfig.consentKey);
    
    if (!consent) {
        // No consent found, show banner
        setTimeout(() => {
            createCookieConsent();
            showCookieConsent();
        }, cookieConfig.showDelay);
    } else {
        // Consent exists, apply preferences
        const consentData = JSON.parse(consent);
        applyCookiePreferences(consentData);
    }
}

// Show cookie consent banner
function showCookieConsent() {
    const banner = document.getElementById('cookieConsent');
    if (banner) {
        banner.classList.add('show');
        
        // Track impression
        if (typeof gtag !== 'undefined') {
            gtag('event', 'cookie_consent_impression', {
                'event_category': 'User Interaction',
                'event_label': 'Cookie Banner Shown'
            });
        }
    }
}

// Hide cookie consent banner
function hideCookieConsent() {
    const banner = document.getElementById('cookieConsent');
    if (banner) {
        banner.classList.remove('show');
        setTimeout(() => {
            banner.remove();
        }, cookieConfig.hideDelay);
    }
}

// Accept all cookies
function acceptCookies() {
    const consentData = {
        accepted: true,
        rejected: false,
        analytics: true,
        marketing: true,
        functional: true,
        timestamp: Date.now()
    };
    
    // Save consent
    localStorage.setItem(cookieConfig.consentKey, JSON.stringify(consentData));
    
    // Apply preferences
    applyCookiePreferences(consentData);
    
    // Hide banner
    hideCookieConsent();
    
    // Track acceptance
    if (typeof gtag !== 'undefined') {
        gtag('event', 'cookie_consent_accepted', {
            'event_category': 'User Interaction',
            'event_label': 'All Cookies Accepted'
        });
    }
    
    // Load analytics scripts
    loadAnalyticsScripts();
}

// Reject all cookies
function rejectCookies() {
    const consentData = {
        accepted: false,
        rejected: true,
        analytics: false,
        marketing: false,
        functional: true, // Essential cookies are always allowed
        timestamp: Date.now()
    };
    
    // Save consent
    localStorage.setItem(cookieConfig.consentKey, JSON.stringify(consentData));
    
    // Apply preferences
    applyCookiePreferences(consentData);
    
    // Hide banner
    hideCookieConsent();
    
    // Track rejection
    if (typeof gtag !== 'undefined') {
        gtag('event', 'cookie_consent_rejected', {
            'event_category': 'User Interaction',
            'event_label': 'All Cookies Rejected'
        });
    }
    
    // Remove analytics cookies
    removeAnalyticsCookies();
}

// Show cookie settings modal
function showCookieSettings() {
    const settingsHtml = `
        <div id="cookieSettingsModal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Cookie Settings</h2>
                    <button type="button" class="modal-close" onclick="closeCookieSettings()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="cookie-category">
                        <div class="category-header">
                            <h3>Essential Cookies</h3>
                            <div class="toggle-switch">
                                <input type="checkbox" id="essentialCookies" checked disabled>
                                <label for="essentialCookies"></label>
                            </div>
                        </div>
                        <p>These cookies are necessary for the website to function and cannot be switched off.</p>
                    </div>
                    
                    <div class="cookie-category">
                        <div class="category-header">
                            <h3>Analytics Cookies</h3>
                            <div class="toggle-switch">
                                <input type="checkbox" id="analyticsCookies">
                                <label for="analyticsCookies"></label>
                            </div>
                        </div>
                        <p>Help us understand how visitors interact with our website by collecting and reporting information.</p>
                    </div>
                    
                    <div class="cookie-category">
                        <div class="category-header">
                            <h3>Marketing Cookies</h3>
                            <div class="toggle-switch">
                                <input type="checkbox" id="marketingCookies">
                                <label for="marketingCookies"></label>
                            </div>
                        </div>
                        <p>Used to deliver advertisements that are relevant to you and your interests.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-cookie btn-secondary" onclick="closeCookieSettings()">Cancel</button>
                    <button type="button" class="btn-cookie btn-primary" onclick="saveCookieSettings()">Save Preferences</button>
                </div>
            </div>
        </div>
    `;
    
    // Add modal to page
    const container = document.createElement('div');
    container.innerHTML = settingsHtml;
    document.body.appendChild(container.firstElementChild);
    
    // Show modal
    setTimeout(() => {
        document.getElementById('cookieSettingsModal').classList.add('show');
    }, 100);
}

// Close cookie settings modal
function closeCookieSettings() {
    const modal = document.getElementById('cookieSettingsModal');
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.remove();
        }, 300);
    }
}

// Save cookie settings
function saveCookieSettings() {
    const consentData = {
        accepted: true,
        rejected: false,
        analytics: document.getElementById('analyticsCookies').checked,
        marketing: document.getElementById('marketingCookies').checked,
        functional: true,
        timestamp: Date.now()
    };
    
    // Save consent
    localStorage.setItem(cookieConfig.consentKey, JSON.stringify(consentData));
    
    // Apply preferences
    applyCookiePreferences(consentData);
    
    // Close modals
    closeCookieSettings();
    hideCookieConsent();
    
    // Track custom settings
    if (typeof gtag !== 'undefined') {
        gtag('event', 'cookie_consent_custom', {
            'event_category': 'User Interaction',
            'event_label': 'Custom Cookie Settings'
        });
    }
    
    // Load analytics if accepted
    if (consentData.analytics) {
        loadAnalyticsScripts();
    } else {
        removeAnalyticsCookies();
    }
}

// Apply cookie preferences
function applyCookiePreferences(consentData) {
    // Update body class for styling
    document.body.classList.toggle('cookies-accepted', consentData.accepted);
    document.body.classList.toggle('cookies-rejected', consentData.rejected);
    
    // Apply analytics consent
    if (consentData.analytics) {
        loadAnalyticsScripts();
    } else {
        removeAnalyticsCookies();
    }
}

// Load analytics scripts
function loadAnalyticsScripts() {
    // Google Analytics
    if (!document.querySelector('script[src*="googletagmanager"]')) {
        const gtagScript = document.createElement('script');
        gtagScript.async = true;
        gtagScript.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
        document.head.appendChild(gtagScript);
        
        // Initialize gtag
        window.dataLayer = window.dataLayer || [];
        window.gtag = function() {
            dataLayer.push(arguments);
        };
        gtag('js', new Date());
        gtag('config', 'G-XXXXXXXXXX', {
            'anonymize_ip': true,
            'cookie_domain': 'autotester-egypt.com'
        });
    }
}

// Remove analytics cookies
function removeAnalyticsCookies() {
    const cookies = ['_ga', '_gid', '_gat', '_gac', '_gid'];
    cookies.forEach(cookie => {
        document.cookie = `${cookie}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.autotester-egypt.com;`;
    });
}

// Reset cookie consent
function resetCookieConsent() {
    localStorage.removeItem(cookieConfig.consentKey);
    removeAnalyticsCookies();
    checkCookieConsent();
}

// Check if user is from EU (GDPR applies)
function isEUCountry() {
    // This is a simplified check. In production, you'd use a proper IP geolocation service
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    const eutimezones = ['Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Rome', 'Europe/Madrid', 'Europe/Amsterdam'];
    return eutimezones.some(tz => timezone.startsWith(tz.replace('Europe/', '')));
}

// Initialize cookie consent
function initCookieConsent() {
    // Only show consent banner for EU users or if forced
    const forceConsent = new URLSearchParams(window.location.search).get('force-consent');
    
    if (isEUCountry() || forceConsent === 'true') {
        checkCookieConsent();
    } else {
        // Non-EU users get automatic consent
        acceptCookies();
    }
}

// Export functions for global use
window.acceptCookies = acceptCookies;
window.rejectCookies = rejectCookies;
window.showCookieSettings = showCookieSettings;
window.resetCookieConsent = resetCookieConsent;

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', initCookieConsent);

// Handle page visibility changes
document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
        checkCookieConsent();
    }
});
