<!-- Ajouter cette section en temps réel au dashboard -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card border-0 shadow-lg">
            <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <h4 class="mb-0">🔴 Monitoring en Temps Réel</h4>
                <small>Mise à jour automatique toutes les 30 secondes</small>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-md-3">
                        <div class="p-3 bg-success-subtle rounded">
                            <h2 id="activeVisitors" class="text-success mb-1">-</h2>
                            <small class="text-muted">Visiteurs Actifs</small>
                            <div class="small text-success">🟢 Dernières 5 min</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-info-subtle rounded">
                            <h2 id="realtimeViews" class="text-info mb-1">-</h2>
                            <small class="text-muted">Vues/Heure</small>
                            <div class="small text-info">📈 Dernière heure</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-warning-subtle rounded">
                            <h2 id="realtimeEvents" class="text-warning mb-1">-</h2>
                            <small class="text-muted">Événements/Heure</small>
                            <div class="small text-warning">⚡ Interactions</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-danger-subtle rounded">
                            <h2 id="avgResponseTime" class="text-danger mb-1">-</h2>
                            <small class="text-muted">Temps Réponse</small>
                            <div class="small text-danger">⏱️ Moyenne</div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-md-8">
                        <canvas id="realtimeChart" height="100"></canvas>
                    </div>
                    <div class="col-md-4">
                        <h6 class="text-muted">🚀 Activité Récente</h6>
                        <div id="recentActivity" style="max-height: 200px; overflow-y: auto;">
                            <div class="text-center text-muted">Chargement...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Chart en temps réel
let realtimeChart;

function initRealtimeChart() {
    const ctx = document.getElementById('realtimeChart').getContext('2d');
    realtimeChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Visites',
                data: [],
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                fill: true,
                tension: 0.4
            }, {
                label: 'Événements',
                data: [],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Activité des 60 Dernières Minutes'
                }
            }
        }
    });
}

// Mettre à jour les données temps réel
async function updateRealTimeData() {
    try {
        const response = await fetch('/services/api-analytics.php?action=live_stats');
        const data = await response.json();
        
        if (data.error) {
            console.error('Erreur API:', data.error);
            return;
        }
        
        // Mettre à jour les compteurs
        document.getElementById('activeVisitors').textContent = data.active_visitors?.active_count || '0';
        
        // Calculer total des visites de l'heure
        const hourlyTotal = data.hourly_activity?.reduce((sum, item) => sum + parseInt(item.visits), 0) || 0;
        document.getElementById('realtimeViews').textContent = hourlyTotal;
        
        // Calculer total des événements
        const eventsTotal = data.event_types?.reduce((sum, item) => sum + parseInt(item.count), 0) || 0;
        document.getElementById('realtimeEvents').textContent = eventsTotal;
        
        // Temps de réponse moyen
        const avgTime = data.avg_performance?.avg_load_time ? 
            Math.round(data.avg_performance.avg_load_time) + 'ms' : 'N/A';
        document.getElementById('avgResponseTime').textContent = avgTime;
        
        // Mettre à jour le graphique
        if (realtimeChart && data.hourly_activity) {
            const labels = data.hourly_activity.map(item => item.time_slot);
            const visits = data.hourly_activity.map(item => parseInt(item.visits));
            
            realtimeChart.data.labels = labels;
            realtimeChart.data.datasets[0].data = visits;
            realtimeChart.update('none'); // Animation désactivée pour temps réel
        }
        
        // Mettre à jour l'activité récente
        updateRecentActivity();
        
    } catch (error) {
        console.error('Erreur mise à jour temps réel:', error);
    }
}

// Mettre à jour l'activité récente
async function updateRecentActivity() {
    try {
        const [visitsResponse, eventsResponse] = await Promise.all([
            fetch('/services/api-analytics.php?action=recent_visits'),
            fetch('/services/api-analytics.php?action=recent_events')
        ]);
        
        const visits = await visitsResponse.json();
        const events = await eventsResponse.json();
        
        let html = '';
        
        // Mélanger visites et événements par timestamp
        const allActivity = [
            ...(visits.visits || []).map(v => ({...v, type: 'visit', time: v.created_at})),
            ...(events.events || []).map(e => ({...e, type: 'event', time: e.created_at}))
        ].sort((a, b) => new Date(b.time) - new Date(a.time)).slice(0, 10);
        
        allActivity.forEach(item => {
            const timeAgo = getTimeAgo(item.time);
            if (item.type === 'visit') {
                html += `
                    <div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
                        <div>
                            <span class="badge bg-success me-2">👀</span>
                            <small><strong>${item.page_title || 'Page sans titre'}</strong></small>
                        </div>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                `;
            } else {
                html += `
                    <div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
                        <div>
                            <span class="badge bg-primary me-2">⚡</span>
                            <small>${item.event_action} (${item.event_category})</small>
                        </div>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                `;
            }
        });
        
        document.getElementById('recentActivity').innerHTML = html || '<div class="text-muted text-center">Aucune activité récente</div>';
        
    } catch (error) {
        console.error('Erreur activité récente:', error);
    }
}

// Calculer le temps écoulé
function getTimeAgo(timestamp) {
    const now = new Date();
    const time = new Date(timestamp);
    const diffMs = now - time;
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 1) return 'À l\'instant';
    if (diffMins < 60) return `Il y a ${diffMins}min`;
    
    const diffHours = Math.floor(diffMins / 60);
    if (diffHours < 24) return `Il y a ${diffHours}h`;
    
    const diffDays = Math.floor(diffHours / 24);
    return `Il y a ${diffDays}j`;
}

// Initialisation du monitoring temps réel
document.addEventListener('DOMContentLoaded', function() {
    // Attendre que Chart.js soit chargé
    if (typeof Chart !== 'undefined') {
        initRealtimeChart();
        updateRealTimeData();
        
        // Mise à jour automatique toutes les 30 secondes
        setInterval(updateRealTimeData, 30000);
    }
});
</script>