/**
 * Système de tracking SERVICES-AE Analytics
 * Collecte automatiquement les données de navigation et événements
 */
(function() {
    'use strict';
    
    // Configuration
    const TRACKING_CONFIG = {
        endpoint: window.location.pathname.startsWith('/services/') ? '/services/track.php' : 'services/track.php',
        enableAutoTracking: true,
        enablePerformanceTracking: true,
        enableEventTracking: true,
        debug: false
    };
    
    // Variables globales
    let pageLoadTime = Date.now();
    let trackingQueue = [];
    let isOnline = navigator.onLine;
    
    /**
     * Log de debug
     */
    function debug(...args) {
        if (TRACKING_CONFIG.debug) {
            console.log('[SERVICES-AE Analytics]', ...args);
        }
    }
    
    /**
     * Envoyer des données au serveur
     */
    function sendData(data, retries = 3) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', TRACKING_CONFIG.endpoint, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        debug('Données envoyées:', data);
                        resolve(xhr.responseText);
                    } else if (retries > 0 && isOnline) {
                        // Retry avec délai exponentiel
                        setTimeout(() => {
                            sendData(data, retries - 1).then(resolve).catch(reject);
                        }, Math.pow(2, 3 - retries) * 1000);
                    } else {
                        debug('Erreur envoi:', xhr.status, xhr.statusText);
                        reject(new Error('Echec envoi: ' + xhr.status));
                    }
                }
            };
            
            xhr.onerror = function() {
                if (retries > 0) {
                    setTimeout(() => {
                        sendData(data, retries - 1).then(resolve).catch(reject);
                    }, Math.pow(2, 3 - retries) * 1000);
                } else {
                    reject(new Error('Erreur réseau'));
                }
            };
            
            try {
                xhr.send(JSON.stringify(data));
            } catch (e) {
                reject(e);
            }
        });
    }
    
    /**
     * Ajouter à la queue avec sauvegarde locale
     */
    function queueTracking(data) {
        trackingQueue.push(data);
        
        // Sauvegarder localement si hors ligne
        if (!isOnline && localStorage) {
            try {
                const stored = JSON.parse(localStorage.getItem('services_analytics_queue') || '[]');
                stored.push(data);
                localStorage.setItem('services_analytics_queue', JSON.stringify(stored));
            } catch (e) {
                debug('Erreur localStorage:', e);
            }
        }
    }
    
    /**
     * Traiter la queue
     */
    function processQueue() {
        if (trackingQueue.length === 0 || !isOnline) return;
        
        const batch = trackingQueue.splice(0, 10); // Traiter par lots de 10
        
        batch.forEach(data => {
            sendData(data).catch(error => {
                debug('Erreur traitement queue:', error);
                // Remettre en queue si échec
                queueTracking(data);
            });
        });
        
        // Continuer le traitement
        if (trackingQueue.length > 0) {
            setTimeout(processQueue, 1000);
        }
    }
    
    /**
     * Récupérer les données stockées localement
     */
    function loadStoredData() {
        if (!localStorage) return;
        
        try {
            const stored = JSON.parse(localStorage.getItem('services_analytics_queue') || '[]');
            trackingQueue = trackingQueue.concat(stored);
            localStorage.removeItem('services_analytics_queue');
            debug('Données récupérées du localStorage:', stored.length, 'éléments');
        } catch (e) {
            debug('Erreur récupération localStorage:', e);
        }
    }
    
    /**
     * Collecter les informations de base
     */
    function getBaseData() {
        return {
            page_url: window.location.href,
            page_title: document.title,
            referrer: document.referrer,
            screen_resolution: screen.width + 'x' + screen.height,
            language: navigator.language || navigator.userLanguage,
            timestamp: new Date().toISOString()
        };
    }
    
    /**
     * Tracker une visite de page
     */
    function trackPageView() {
        if (!TRACKING_CONFIG.enableAutoTracking) return;
        
        const data = {
            action: 'track_visit',
            ...getBaseData()
        };
        
        queueTracking(data);
        debug('Page view trackée:', data);
    }
    
    /**
     * Tracker un événement
     */
    function trackEvent(eventType, category, action, label = '', value = 0) {
        if (!TRACKING_CONFIG.enableEventTracking) return;
        
        const data = {
            action: 'track_event',
            event_type: eventType,
            event_category: category,
            event_action: action,
            event_label: label,
            event_value: value,
            ...getBaseData()
        };
        
        queueTracking(data);
        debug('Événement tracké:', data);
    }
    
    /**
     * Tracker les performances de page
     */
    function trackPerformance() {
        if (!TRACKING_CONFIG.enablePerformanceTracking) return;
        if (!window.performance || !window.performance.timing) return;
        
        setTimeout(() => {
            const timing = window.performance.timing;
            const navigation = window.performance.navigation;
            
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            const domReadyTime = timing.domContentLoadedEventEnd - timing.navigationStart;
            
            // Estimer la taille de la page
            let pageSize = 0;
            try {
                pageSize = new Blob([document.documentElement.outerHTML]).size;
            } catch (e) {
                pageSize = document.documentElement.outerHTML.length;
            }
            
            // Compter les requêtes (approximatif)
            const numRequests = document.querySelectorAll('img, script, link[rel="stylesheet"]').length;
            
            const data = {
                action: 'track_performance',
                load_time: loadTime,
                dom_ready_time: domReadyTime,
                page_size: pageSize,
                num_requests: numRequests,
                navigation_type: navigation.type,
                ...getBaseData()
            };
            
            queueTracking(data);
            debug('Performance trackée:', data);
        }, 1000); // Attendre que la page soit complètement chargée
    }
    
    /**
     * Tracking automatique des événements communs
     */
    function setupAutoEventTracking() {
        // Clics sur les liens externes
        document.addEventListener('click', function(e) {
            const link = e.target.closest('a');
            if (link && link.href) {
                const isExternal = link.hostname !== window.location.hostname;
                if (isExternal) {
                    trackEvent('click', 'external_link', 'outbound', link.href);
                }
            }
        });
        
        // Clics sur les boutons
        document.addEventListener('click', function(e) {
            if (e.target.tagName === 'BUTTON' || e.target.type === 'submit') {
                const buttonText = e.target.textContent || e.target.value || 'Bouton sans texte';
                trackEvent('click', 'button', 'click', buttonText);
            }
        });
        
        // Soumissions de formulaires
        document.addEventListener('submit', function(e) {
            const form = e.target;
            const formId = form.id || form.className || 'Formulaire sans ID';
            trackEvent('form', 'submit', 'form_submission', formId);
        });
        
        // Téléchargements de fichiers
        document.addEventListener('click', function(e) {
            const link = e.target.closest('a');
            if (link && link.href) {
                const fileExtensions = /\.(pdf|doc|docx|xls|xlsx|zip|rar|jpg|jpeg|png|gif|mp4|mp3)$/i;
                if (fileExtensions.test(link.href)) {
                    trackEvent('download', 'file', 'download', link.href);
                }
            }
        });
        
        // Scroll tracking
        let scrollTracked = false;
        window.addEventListener('scroll', function() {
            if (!scrollTracked && window.scrollY > 0) {
                const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
                if (scrollPercent >= 25) {
                    trackEvent('scroll', 'engagement', 'scroll_25_percent', '', scrollPercent);
                    scrollTracked = true;
                }
            }
        });
        
        // Temps passé sur la page
        let timeOnPage = 0;
        const timeInterval = setInterval(() => {
            timeOnPage += 10;
            if (timeOnPage === 30000) { // 30 secondes
                trackEvent('time', 'engagement', 'time_on_page_30s', '', 30);
            } else if (timeOnPage === 60000) { // 1 minute
                trackEvent('time', 'engagement', 'time_on_page_1min', '', 60);
            } else if (timeOnPage === 300000) { // 5 minutes
                trackEvent('time', 'engagement', 'time_on_page_5min', '', 300);
                clearInterval(timeInterval);
            }
        }, 10000);
        
        // Visibilité de la page
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                trackEvent('page', 'visibility', 'page_hidden');
            } else {
                trackEvent('page', 'visibility', 'page_visible');
            }
        });
    }
    
    /**
     * Gestion de la connectivité
     */
    function setupConnectivityHandling() {
        window.addEventListener('online', function() {
            isOnline = true;
            debug('Connexion rétablie');
            loadStoredData();
            processQueue();
        });
        
        window.addEventListener('offline', function() {
            isOnline = false;
            debug('Connexion perdue');
        });
    }
    
    /**
     * Initialisation
     */
    function init() {
        debug('Initialisation du tracking SERVICES-AE Analytics');
        
        // Charger les données stockées
        loadStoredData();
        
        // Configurer la connectivité
        setupConnectivityHandling();
        
        // Tracker la page actuelle
        trackPageView();
        
        // Tracker les performances
        trackPerformance();
        
        // Configurer le tracking automatique
        setupAutoEventTracking();
        
        // Traiter la queue régulièrement
        setInterval(processQueue, 5000);
        
        // Traitement initial de la queue
        if (isOnline) {
            setTimeout(processQueue, 1000);
        }
        
        debug('Tracking initialisé avec succès');
    }
    
    // API publique
    window.ServicesAnalytics = {
        trackEvent: trackEvent,
        trackPageView: trackPageView,
        config: TRACKING_CONFIG,
        debug: debug
    };
    
    // Initialiser quand le DOM est prêt
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    
    // Sauvegarder les données avant de quitter la page
    window.addEventListener('beforeunload', function() {
        if (trackingQueue.length > 0 && localStorage) {
            try {
                const stored = JSON.parse(localStorage.getItem('services_analytics_queue') || '[]');
                const allData = stored.concat(trackingQueue);
                localStorage.setItem('services_analytics_queue', JSON.stringify(allData));
            } catch (e) {
                debug('Erreur sauvegarde beforeunload:', e);
            }
        }
    });
    
})();