document.addEventListener('DOMContentLoaded', function() {
    // Configuration et variables
    let apiUrl = localStorage.getItem('umamiApiUrl') || '';
    let apiKey = localStorage.getItem('umamiApiKey') || '';
    let selectedWebsiteId = '';
    let websitesList = [];
    let currentTimeframe = '7d'; // Default timeframe
    
    // Éléments DOM
    const apiUrlInput = document.getElementById('umami-api-url');
    const apiKeyInput = document.getElementById('umami-api-key');
    const saveApiConfigBtn = document.getElementById('save-api-config');
    const websiteSelect = document.getElementById('website-select');
    const timeframeSelector = document.getElementById('timeframe-selector');
    const refreshBtn = document.getElementById('refresh-analytics');
    
    // Initialisation
    function init() {
        // Charger les configurations sauvegardées
        if (apiUrl && apiKey) {
            apiUrlInput.value = apiUrl;
            apiKeyInput.value = apiKey;
            fetchWebsites();
        }
        
        // Attacher les écouteurs d'événements
        saveApiConfigBtn.addEventListener('click', saveApiConfig);
        websiteSelect.addEventListener('change', handleWebsiteChange);
        timeframeSelector.addEventListener('change', handleTimeframeChange);
        refreshBtn.addEventListener('click', refreshData);
        
        // Si l'onglet Visits est activé, charger les données
        document.querySelector('.visits-tab').addEventListener('click', function() {
            if (apiUrl && apiKey) {
                fetchWebsites();
            }
        });
    }
    
    // Sauvegarder la configuration API
    function saveApiConfig() {
        const newApiUrl = apiUrlInput.value.trim();
        const newApiKey = apiKeyInput.value.trim();
        
        if (!newApiUrl || !newApiKey) {
            showNotification('Both API URL and API Key are required', 'error');
            return;
        }
        
        apiUrl = newApiUrl;
        apiKey = newApiKey;
        localStorage.setItem('umamiApiUrl', apiUrl);
        localStorage.setItem('umamiApiKey', apiKey);
        
        showNotification('API configuration saved', 'success');
        fetchWebsites();
    }
    
    // Récupérer la liste des sites web
    function fetchWebsites() {
        if (!apiUrl || !apiKey) return;
        
        showLoading('website-select');
        
        fetch(`${apiUrl}/websites`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`API returned ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            websitesList = data;
            populateWebsiteDropdown(data);
        })
        .catch(error => {
            console.error('Error fetching websites:', error);
            showNotification('Failed to fetch websites. Check your API configuration.', 'error');
            websiteSelect.innerHTML = '<option value="">Error loading websites</option>';
        });
    }
    
    // Remplir le menu déroulant des sites web
    function populateWebsiteDropdown(websites) {
        if (!websites || websites.length === 0) {
            websiteSelect.innerHTML = '<option value="">No websites found</option>';
            return;
        }
        
        websiteSelect.innerHTML = '<option value="">Select a website</option>';
        websites.forEach(site => {
            const option = document.createElement('option');
            option.value = site.id;
            option.textContent = site.name;
            websiteSelect.appendChild(option);
        });
        
        // Si un site était précédemment sélectionné, le restaurer
        if (selectedWebsiteId && websites.some(site => site.id === selectedWebsiteId)) {
            websiteSelect.value = selectedWebsiteId;
            loadWebsiteStats(selectedWebsiteId);
        }
    }
    
    // Gestionnaire de changement de site web
    function handleWebsiteChange() {
        selectedWebsiteId = websiteSelect.value;
        if (selectedWebsiteId) {
            loadWebsiteStats(selectedWebsiteId);
        } else {
            resetStats();
        }
    }
    
    // Gestionnaire de changement de période
    function handleTimeframeChange() {
        currentTimeframe = timeframeSelector.value;
        if (selectedWebsiteId) {
            loadWebsiteStats(selectedWebsiteId);
        }
    }
    
    // Recharger les données
    function refreshData() {
        if (selectedWebsiteId) {
            loadWebsiteStats(selectedWebsiteId);
        } else if (apiUrl && apiKey) {
            fetchWebsites();
        }
    }
    
    // Charger les statistiques d'un site web
    function loadWebsiteStats(websiteId) {
        if (!apiUrl || !apiKey || !websiteId) return;
        
        const params = getTimeframeParams(currentTimeframe);
        
        // Réinitialiser les éléments UI
        resetStats();
        showLoading('stats-overview');
        
        // Récupérer les statistiques
        Promise.all([
            fetchSiteStats(websiteId, params),
            fetchSitePages(websiteId, params),
            fetchSiteReferrers(websiteId, params),
            fetchSiteBrowsers(websiteId, params),
            fetchSiteDevices(websiteId, params)
        ])
        .then(([stats, pages, referrers, browsers, devices]) => {
            displayStats(stats);
            displayPages(pages);
            displayReferrers(referrers);
            displayDevices(browsers, devices);
            renderVisitorsChart(websiteId, params);
        })
        .catch(error => {
            console.error('Error loading website stats:', error);
            showNotification('Failed to load website statistics', 'error');
        });
    }
    
    // Récupérer les paramètres de période
    function getTimeframeParams(timeframe) {
        const now = new Date();
        let startDate;
        
        switch (timeframe) {
            case '24h':
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 1);
                break;
            case '7d':
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 7);
                break;
            case '30d':
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 30);
                break;
            case '6m':
                startDate = new Date(now);
                startDate.setMonth(now.getMonth() - 6);
                break;
            default:
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 7);
        }
        
        return {
            startAt: Math.floor(startDate.getTime() / 1000),
            endAt: Math.floor(now.getTime() / 1000),
            unit: timeframe === '24h' ? 'hour' : timeframe === '6m' ? 'month' : 'day'
        };
    }
    
    // Appels API pour récupérer les statistiques
    function fetchSiteStats(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/stats?startAt=${params.startAt}&endAt=${params.endAt}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    function fetchSitePages(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/pages?startAt=${params.startAt}&endAt=${params.endAt}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    function fetchSiteReferrers(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/referrers?startAt=${params.startAt}&endAt=${params.endAt}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    function fetchSiteBrowsers(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/browsers?startAt=${params.startAt}&endAt=${params.endAt}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    function fetchSiteDevices(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/devices?startAt=${params.startAt}&endAt=${params.endAt}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    function fetchVisitorsTimeSeries(websiteId, params) {
        return fetch(`${apiUrl}/websites/${websiteId}/stats?startAt=${params.startAt}&endAt=${params.endAt}&unit=${params.unit}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error(`API returned ${response.status}`);
            return response.json();
        });
    }
    
    // Afficher les statistiques
    function displayStats(stats) {
        if (!stats) return;
        
        const pageViewsElement = document.getElementById('page-views-count');
        const visitorsElement = document.getElementById('visitors-count');
        const bounceRateElement = document.getElementById('bounce-rate');
        const avgDurationElement = document.getElementById('avg-duration');
        
        pageViewsElement.textContent = stats.pageviews.value || '0';
        visitorsElement.textContent = stats.uniques.value || '0';
        
        const bounceRate = stats.bounces ? Math.round((stats.bounces.value / stats.visits.value) * 100) : 0;
        bounceRateElement.textContent = `${bounceRate}%`;
        
        const avgDuration = stats.totaltime && stats.visits ? Math.round((stats.totaltime.value / stats.visits.value)) : 0;
        const minutes = Math.floor(avgDuration / 60);
        const seconds = avgDuration % 60;
        avgDurationElement.textContent = `${minutes}m ${seconds}s`;
    }
    
    // Afficher les pages les plus visitées
    function displayPages(pages) {
        const pagesListElement = document.getElementById('pages-list');
        pagesListElement.innerHTML = '';
        
        if (!pages || pages.length === 0) {
            pagesListElement.innerHTML = '<div class="text-center text-gray-500 p-4">No page data available</div>';
            return;
        }
        
        pages.slice(0, 10).forEach(page => {
            const pageItem = document.createElement('div');
            pageItem.classList.add('flex', 'justify-between', 'items-center', 'p-2', 'hover:bg-gray-100', 'dark:hover:bg-gray-800', 'rounded');
            
            const pageUrl = page.url.length > 30 ? page.url.substring(0, 30) + '...' : page.url;
            
            pageItem.innerHTML = `
                <div class="flex items-center space-x-2">
                    <i class="fas fa-file-alt text-gray-500"></i>
                    <span title="${page.url}">${pageUrl}</span>
                </div>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <i class="fas fa-eye"></i> ${page.pageviews}
                    </div>
                    <div class="text-sm text-gray-500">
                        <i class="fas fa-users"></i> ${page.uniques}
                    </div>
                </div>
            `;
            
            pagesListElement.appendChild(pageItem);
        });
    }
    
    // Afficher les sources de référence
    function displayReferrers(referrers) {
        const referrersListElement = document.getElementById('referrers-list');
        referrersListElement.innerHTML = '';
        
        if (!referrers || referrers.length === 0) {
            referrersListElement.innerHTML = '<div class="text-center text-gray-500 p-4">No referrer data available</div>';
            return;
        }
        
        referrers.slice(0, 10).forEach(referrer => {
            const referrerItem = document.createElement('div');
            referrerItem.classList.add('flex', 'justify-between', 'items-center', 'p-2', 'hover:bg-gray-100', 'dark:hover:bg-gray-800', 'rounded');
            
            const referrerName = referrer.referrer === '' ? 'Direct / None' : 
                                referrer.referrer.length > 30 ? referrer.referrer.substring(0, 30) + '...' : 
                                referrer.referrer;
            
            referrerItem.innerHTML = `
                <div class="flex items-center space-x-2">
                    <i class="fas fa-link text-gray-500"></i>
                    <span title="${referrer.referrer}">${referrerName}</span>
                </div>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <i class="fas fa-users"></i> ${referrer.visitors}
                    </div>
                    <div class="text-sm text-gray-500">
                        <i class="fas fa-eye"></i> ${referrer.pageviews}
                    </div>
                </div>
            `;
            
            referrersListElement.appendChild(referrerItem);
        });
    }
    
    // Afficher les navigateurs et appareils
    function displayDevices(browsers, devices) {
        const devicesChartElement = document.getElementById('devices-chart');
        
        if (!browsers || !browsers.length || !devices || !devices.length) {
            devicesChartElement.innerHTML = '<div class="text-center text-gray-500 p-4">No device data available</div>';
            return;
        }
        
        // Préparation des données pour le graphique
        const browsersData = browsers.slice(0, 5).map(browser => ({
            name: browser.browser,
            value: browser.visitors
        }));
        
        const devicesData = devices.slice(0, 5).map(device => ({
            name: device.device,
            value: device.visitors
        }));
        
        // Création du graphique avec Chart.js
        const ctx = document.createElement('canvas');
        devicesChartElement.innerHTML = '';
        devicesChartElement.appendChild(ctx);
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: [...devicesData.map(d => d.name)],
                datasets: [
                    {
                        data: [...devicesData.map(d => d.value)],
                        backgroundColor: [
                            '#4F46E5', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
                            '#EC4899', '#3B82F6', '#6366F1', '#14B8A6', '#F97316'
                        ]
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
                        }
                    },
                    title: {
                        display: true,
                        text: 'Devices',
                        color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
                    }
                }
            }
        });
    }
    
    // Créer le graphique des visiteurs
    function renderVisitorsChart(websiteId, params) {
        const visitorsChartElement = document.getElementById('visitors-chart');
        
        fetchVisitorsTimeSeries(websiteId, params)
            .then(data => {
                if (!data || !data.sessions) {
                    visitorsChartElement.innerHTML = '<div class="text-center text-gray-500 p-4">No visitor data available</div>';
                    return;
                }
                
                // Convertir les données de la série temporelle
                const timeSeries = data.sessions;
                const labels = [];
                const visitors = [];
                const pageviews = [];
                
                for (const date in timeSeries) {
                    const formattedDate = formatDate(date, params.unit);
                    labels.push(formattedDate);
                    visitors.push(timeSeries[date].uniques);
                    pageviews.push(timeSeries[date].pageviews);
                }
                
                // Création du graphique avec Chart.js
                const ctx = document.createElement('canvas');
                visitorsChartElement.innerHTML = '';
                visitorsChartElement.appendChild(ctx);
                
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: 'Visitors',
                                data: visitors,
                                borderColor: '#3B82F6',
                                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                                borderWidth: 2,
                                fill: true,
                                tension: 0.4
                            },
                            {
                                label: 'Page Views',
                                data: pageviews,
                                borderColor: '#10B981',
                                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                                borderWidth: 2,
                                fill: true,
                                tension: 0.4
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'top',
                                labels: {
                                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
                                }
                            }
                        },
                        scales: {
                            x: {
                                grid: {
                                    color: document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'
                                },
                                ticks: {
                                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
                                }
                            },
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'
                                },
                                ticks: {
                                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
                                }
                            }
                        }
                    }
                });
            })
            .catch(error => {
                console.error('Error loading visitors time series:', error);
                visitorsChartElement.innerHTML = '<div class="text-center text-gray-500 p-4">Failed to load visitor data</div>';
            });
    }
    
    // Formater les dates pour l'affichage
    function formatDate(dateStr, unit) {
        const date = new Date(dateStr);
        
        switch (unit) {
            case 'hour':
                return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            case 'day':
                return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
            case 'month':
                return date.toLocaleDateString([], { month: 'short', year: 'numeric' });
            default:
                return date.toLocaleDateString();
        }
    }
    
    // Afficher une notification
    function showNotification(message, type = 'success') {
        const notificationClass = type === 'success' ? 'success-notification' : 'error-notification';
        const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        const bgColorClass = type === 'success' ? 'bg-green-500 dark:bg-green-600' : 'bg-red-500 dark:bg-red-600';
        
        const notification = document.createElement('div');
        notification.className = `${notificationClass} fixed top-4 right-4 ${bgColorClass} text-white px-6 py-3 rounded-lg shadow-lg z-50`;
        notification.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas ${iconClass}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Supprimer la notification après quelques secondes
        setTimeout(() => {
            notification.classList.add('fade-out');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }
    
    // Afficher un indicateur de chargement
    function showLoading(elementId) {
        const element = document.getElementById(elementId);
        if (!element) return;
        
        if (elementId === 'website-select') {
            element.innerHTML = '<option value="">Loading websites...</option>';
        } else if (elementId === 'stats-overview') {
            document.getElementById('page-views-count').textContent = '--';
            document.getElementById('visitors-count').textContent = '--';
            document.getElementById('bounce-rate').textContent = '--';
            document.getElementById('avg-duration').textContent = '--';
            
            document.getElementById('pages-list').innerHTML = '<div class="text-center text-gray-500 p-4">Loading pages data...</div>';
            document.getElementById('referrers-list').innerHTML = '<div class="text-center text-gray-500 p-4">Loading referrers data...</div>';
            document.getElementById('visitors-chart').innerHTML = '<div class="flex justify-center items-center h-full"><div class="animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-black dark:border-t-white"></div></div>';
            document.getElementById('devices-chart').innerHTML = '<div class="flex justify-center items-center h-full"><div class="animate-spin rounded-full h-8 w-8 border-2 border-gray-300 border-t-black dark:border-t-white"></div></div>';
        }
    }
    
    // Réinitialiser les statistiques
    function resetStats() {
        document.getElementById('page-views-count').textContent = '--';
        document.getElementById('visitors-count').textContent = '--';
        document.getElementById('bounce-rate').textContent = '--';
        document.getElementById('avg-duration').textContent = '--';
        document.getElementById('pageviews-trend').textContent = '--';
        document.getElementById('visitors-trend').textContent = '--';
        document.getElementById('bounce-trend').textContent = '--';
        document.getElementById('duration-trend').textContent = '--';
        
        document.getElementById('pages-list').innerHTML = '<div class="text-center text-gray-500 p-4">Select a website to view top pages</div>';
        document.getElementById('referrers-list').innerHTML = '<div class="text-center text-gray-500 p-4">Select a website to view referrers</div>';
        document.getElementById('visitors-chart').innerHTML = '<div class="text-center text-gray-500 p-4">Select a website to view visitor data</div>';
        document.getElementById('devices-chart').innerHTML = '<div class="text-center text-gray-500 p-4">Select a website to view device data</div>';
    }
    
    // Initialiser le module
    init();
});