function formatNumber(number) {
    if (number < 1000) return number.toString();
    
    const units = ['', 'K', 'M', 'B', 'T'];
    const pow = Math.floor(Math.log(number) / Math.log(1000));
    const value = number / Math.pow(1000, pow);
    
    return value.toFixed(value >= 10 ? 0 : 1) + units[pow];
}

function updateRealtimeCount(count) {
    document.getElementById('pagevico-realtime-count').textContent = formatNumber(count);
}

// Store realtime data for the chart
const realtimeData = {
    labels: Array(30).fill(''),
    datasets: [
        {
            label: 'Active Visitors',
            data: Array(30).fill(0),
            borderColor: 'rgba(255, 107, 0, 1)',
            backgroundColor: 'rgba(255, 107, 0, 0.1)',
            fill: true,
            tension: 0.5
        },
        {
            label: 'Active Sessions',
            data: Array(30).fill(0),
            borderColor: 'rgba(255, 176, 0, 1)',
            backgroundColor: 'rgba(255, 176, 0, 0.1)',
            fill: true,
            tension: 0.5
        }
    ]
};

// Initialize realtime chart
let realtimeChart;
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('pagevicoRealtimeChart');
    if (!ctx) return;
    
    realtimeChart = new Chart(ctx, {
        type: 'line',
        data: realtimeData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { precision: 0 }
                }
            },
            layout: {
                padding: {
                    left: 10,
                    right: 10,
                    top: 20,
                    bottom: 10
                }
            },
            animation: {
                duration: 800
            }
        }
    });

    // Load historical data first
    fetchHistoricalData();
});

function fetchHistoricalData() {
    const url = new URL(pagevicoTracker.realtime_url);
    url.searchParams.append('_wpnonce', pagevicoTracker.nonce);
    url.searchParams.append('historical', 'true');

    fetch(url, {
        method: 'GET',
        credentials: 'include',
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
    })
    .then((data) => {
        if (data.success && data.historical_data) {
            // Clear existing data
            realtimeData.labels = [];
            realtimeData.datasets[0].data = [];
            realtimeData.datasets[1].data = [];

            // Fill with historical data
            data.historical_data.forEach(point => {
                const date = new Date(point.timestamp);
                const timeLabel = date.getHours() + ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
                
                realtimeData.labels.push(timeLabel);
                realtimeData.datasets[0].data.push(point.visitors);
                realtimeData.datasets[1].data.push(point.sessions);
            });

            // Get the last historical data point's values
            const lastPoint = data.historical_data[data.historical_data.length - 1];
            const lastVisitors = lastPoint ? lastPoint.visitors : 0;
            const lastSessions = lastPoint ? lastPoint.sessions : 0;

            // Fill remaining slots with the last historical values
            const remainingSlots = 30 - realtimeData.labels.length;
            for (let i = 0; i < remainingSlots; i++) {
                const now = new Date();
                const timeLabel = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
                
                realtimeData.labels.push(timeLabel);
                realtimeData.datasets[0].data.push(lastVisitors);
                realtimeData.datasets[1].data.push(lastSessions);
            }

            realtimeChart.update();
        }
    })
    .catch((error) => {
        console.error('Error fetching historical data:', error);
    });
}

function fetchRealtimeVisitors() {
    // Check if we're on the dashboard page before making the request
    if (!document.getElementById('pagevicoRealtimeChart')) {
        return; // Exit if we're not on the dashboard page with the chart
    }
    const url = new URL(pagevicoTracker.realtime_url);
    url.searchParams.append('_wpnonce', pagevicoTracker.nonce);
    fetch(url, {
        method: 'GET',
        credentials: 'include',
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
    })
    .then((data) => {
        if (data.success && data.active_visitors !== undefined) {
            updateRealtimeCount(data.active_visitors);
            
            // Update chart data
            if (realtimeChart) {
                // Add timestamp to labels - use current time
                const now = new Date();
                const timeLabel = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
                
                // Remove first element and add new value to end
                realtimeData.labels.shift();
                realtimeData.labels.push(timeLabel);
                
                // Update visitors data
                realtimeData.datasets[0].data.shift();
                realtimeData.datasets[0].data.push(data.active_visitors);
                
                // Update sessions data
                realtimeData.datasets[1].data.shift();
                realtimeData.datasets[1].data.push(data.active_sessions || 0);
                
                realtimeChart.update();
            }
        }
    })
    .catch((error) => {
        console.error('Error fetching realtime visitors:', error);
    });
}

// Start realtime updates after a short delay to allow historical data to load
setTimeout(() => {
    setInterval(fetchRealtimeVisitors, 10000);
}, 1000);