(function() {
    'use strict';
    
    // DOM elements
    const startEl = document.getElementById('spdfed-start');
    const endEl = document.getElementById('spdfed-end');
    const fileFilterEl = document.getElementById('spdfed-file-filter');
    const uniqueEl = document.getElementById('spdfed-unique');
    const refreshBtn = document.getElementById('spdfed-refresh');
    
    // KPI elements
    const kpiTotal = document.getElementById('spdfed-kpi-total');
    const kpiUnique = document.getElementById('spdfed-kpi-unique');
    const kpiAvg = document.getElementById('spdfed-kpi-avg');
    const kpiDays = document.getElementById('spdfed-kpi-days');
    
    // Chart and top files
    const chartCanvas = document.getElementById('spdfed-chart');
    const topFilesEl = document.getElementById('spdfed-top-files');
    
    let chart = null;
    
    /**
     * Fetch analytics data from REST API
     */
    async function fetchAnalyticsData() {
        const params = new URLSearchParams({
            start: startEl.value,
            end: endEl.value,
            unique: uniqueEl.checked ? '1' : '0'
        });
        
        // Handle file filter
        const fileFilter = fileFilterEl.value;
        if (fileFilter) {
            if (fileFilter.startsWith('post_')) {
                params.append('post_id', fileFilter.replace('post_', ''));
            } else if (fileFilter.startsWith('file_')) {
                params.append('file_name', decodeURIComponent(fileFilter.replace('file_', '')));
            }
        }
        
        const response = await fetch(
            SPDFED_ANALYTICS.rest_url + 'analytics/downloads?' + params.toString(),
            {
                headers: {
                    'X-WP-Nonce': SPDFED_ANALYTICS.nonce,
                    'Content-Type': 'application/json'
                }
            }
        );
        
        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || 'Failed to load analytics data');
        }
        
        return await response.json();
    }
    
    /**
     * Render the analytics chart
     */
    function renderChart(data) {
        const ctx = chartCanvas.getContext('2d');
        const labels = data.series.map(item => item.date);
        const values = data.series.map(item => item.count);
        
        if (chart) {
            chart.destroy();
        }
        
        chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: SPDFED_ANALYTICS.strings.downloads,
                    data: values,
                    borderColor: '#0073aa',
                    backgroundColor: 'rgba(0, 115, 170, 0.1)',
                    tension: 0.25,
                    fill: true,
                    pointBackgroundColor: '#0073aa',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                resizeDelay: 0,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: '#ffffff',
                        bodyColor: '#ffffff',
                        borderColor: '#0073aa',
                        borderWidth: 1
                    }
                },
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                scales: {
                    x: {
                        display: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            maxRotation: 45,
                            autoSkip: true,
                            maxTicksLimit: 10
                        }
                    },
                    y: {
                        display: true,
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            precision: 0,
                            callback: function(value) {
                                return Number.isInteger(value) ? value : '';
                            }
                        }
                    }
                }
            }
        });
    }
    
    /**
     * Update KPI displays
     */
    function updateKPIs(data) {
        kpiTotal.textContent = data.totals.downloads.toLocaleString();
        kpiUnique.textContent = data.totals.unique.toLocaleString();
        kpiAvg.textContent = data.totals.avg_per_day.toFixed(1);
        const dayCount = data.totals.days;
        const dayText = dayCount === 1 ? SPDFED_ANALYTICS.strings.day : SPDFED_ANALYTICS.strings.days;
        kpiDays.textContent = dayCount + ' ' + dayText;
    }
    
    /**
     * Render top files list
     */
    function renderTopFiles(files) {
        if (!files || files.length === 0) {
            topFilesEl.innerHTML = '<p style="color: #666; text-align: center; padding: 20px 0;">' + 
                SPDFED_ANALYTICS.strings.no_data + '</p>';
            return;
        }
        
        let html = '<div style="display: grid; gap: 10px;">';
        
        files.forEach((file, index) => {
            const rank = index + 1;
            const title = file.title || file.file_name;
            const downloads = parseInt(file.downloads).toLocaleString();
            
            html += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">
                    <div>
                        <span style="display: inline-block; width: 20px; height: 20px; background: #0073aa; color: white; border-radius: 50%; text-align: center; line-height: 20px; font-size: 12px; font-weight: bold; margin-right: 10px;">${rank}</span>
                        <strong>${title}</strong>
                        ${file.post_id === 0 ? '<span style="background: #e0e0e0; padding: 2px 6px; border-radius: 3px; font-size: 11px; margin-left: 8px;">FREE</span>' : ''}
                    </div>
                    <div style="color: #0073aa; font-weight: 600;">${downloads} downloads</div>
                </div>
            `;
        });
        
        html += '</div>';
        topFilesEl.innerHTML = html;
    }
    
    /**
     * Refresh analytics data
     */
    async function refreshData() {
        refreshBtn.disabled = true;
        refreshBtn.textContent = SPDFED_ANALYTICS.strings.loading;
        
        try {
            const data = await fetchAnalyticsData();
            renderChart(data);
            updateKPIs(data);
            renderTopFiles(data.top_files);
        } catch (error) {
            console.error('Analytics error:', error);
            alert(SPDFED_ANALYTICS.strings.error + ': ' + error.message);
        } finally {
            refreshBtn.disabled = false;
            refreshBtn.innerHTML = '<span class="dashicons dashicons-update" style="margin-right: 5px;vertical-align:-5px;"></span>Refresh';
        }
    }
    
    /**
     * Initialize the analytics page
     */
    function init() {
        if (!startEl || !endEl || !refreshBtn || !chartCanvas) {
            console.error('Analytics: Required elements not found');
            return;
        }
        
        // Event listeners
        refreshBtn.addEventListener('click', refreshData);
        
        // Auto-refresh on filter changes
        [startEl, endEl, fileFilterEl, uniqueEl].forEach(el => {
            if (el) {
                el.addEventListener('change', refreshData);
            }
        });
        
        // Initial load
        refreshData();
    }
    
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
