/**
 * Virtual Files - Analytics Dashboard JavaScript
 * Handles chart rendering and data updates with ApexCharts 5.3.6
 */

(function($) {
    'use strict';

    const VFAnalytics = {
        charts: {},

        /**
         * Initialize analytics dashboard
         */
        init: function() {
            if (!intentdeepVfAnalyticsData || !intentdeepVfAnalyticsData.isPro) {
                // User is not Pro, no charts to initialize
                return;
            }

            this.initCharts();
            this.initEventHandlers();
        },

        /**
         * Initialize all charts
         */
        initCharts: function() {
            if (!window.ApexCharts) {
                console.error('ApexCharts library not loaded');
                return;
            }

            this.renderTimelineChart();
            this.renderFileTypeChart();
            this.renderHourlyChart();
        },

        /**
         * Render Views Over Time Chart (Line Chart)
         */
        renderTimelineChart: function() {
            const container = document.getElementById('vf-timeline-chart');
            if (!container || !intentdeepVfAnalyticsData.data.timeline) {
                return;
            }

            const options = {
                chart: {
                    type: 'area',
                    height: 350,
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',
                    toolbar: {
                        show: true,
                        tools: {
                            download: true,
                            selection: false,
                            zoom: true,
                            zoomin: true,
                            zoomout: true,
                            pan: false,
                            reset: true
                        }
                    },
                    zoom: {
                        enabled: true
                    },
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        },
                        dynamicAnimation: {
                            enabled: true,
                            speed: 350
                        }
                    }
                },
                series: [{
                    name: 'Views',
                    data: intentdeepVfAnalyticsData.data.timeline.data
                }],
                xaxis: {
                    categories: intentdeepVfAnalyticsData.data.timeline.labels.map(date => {
                        // Format date: "Dec 1"
                        const d = new Date(date);
                        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    }),
                    labels: {
                        rotate: -45,
                        rotateAlways: true,
                        hideOverlappingLabels: true,
                        trim: false,
                        style: {
                            fontSize: '11px',
                            colors: '#50575e'
                        }
                    },
                    tickAmount: undefined, // Auto-calculate optimal number of ticks
                    tickPlacement: 'between',
                    axisBorder: {
                        color: '#dcdcde'
                    },
                    axisTicks: {
                        color: '#dcdcde'
                    }
                },
                yaxis: {
                    title: {
                        text: 'Views',
                        style: {
                            fontSize: '12px',
                            fontWeight: 600,
                            color: '#50575e'
                        }
                    },
                    labels: {
                        style: {
                            fontSize: '12px',
                            colors: '#50575e'
                        },
                        formatter: function(val) {
                            return Math.floor(val);
                        }
                    }
                },
                stroke: {
                    curve: 'smooth',
                    width: 3
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.7,
                        opacityTo: 0.2,
                        stops: [0, 90, 100]
                    }
                },
                colors: ['#667eea'],
                dataLabels: {
                    enabled: false
                },
                grid: {
                    borderColor: '#f0f0f1',
                    strokeDashArray: 4,
                    xaxis: {
                        lines: {
                            show: false
                        }
                    }
                },
                tooltip: {
                    theme: 'dark',
                    x: {
                        formatter: function(val, opts) {
                            const date = intentdeepVfAnalyticsData.data.timeline.labels[opts.dataPointIndex];
                            const d = new Date(date);
                            return d.toLocaleDateString('en-US', {
                                weekday: 'short',
                                month: 'short',
                                day: 'numeric',
                                year: 'numeric'
                            });
                        }
                    },
                    y: {
                        formatter: function(val) {
                            return val.toLocaleString() + ' views';
                        }
                    }
                },
                markers: {
                    size: 0,
                    hover: {
                        size: 6
                    }
                }
            };

            this.charts.timeline = new ApexCharts(container, options);
            this.charts.timeline.render();
        },

        /**
         * Render File Type Distribution Chart (Donut Chart)
         */
        renderFileTypeChart: function() {
            const container = document.getElementById('vf-filetype-chart');
            if (!container || !intentdeepVfAnalyticsData.data.fileTypes) {
                return;
            }

            // If no data, show empty state
            if (intentdeepVfAnalyticsData.data.fileTypes.data.length === 0) {
                container.innerHTML = '<div class="vf-no-data" style="padding: 80px 20px; text-align: center; color: #787c82;">' +
                    'No data available yet. File type distribution will appear here once files are accessed.</div>';
                return;
            }

            const options = {
                chart: {
                    type: 'donut',
                    height: 380,
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800
                    }
                },
                series: intentdeepVfAnalyticsData.data.fileTypes.data,
                labels: intentdeepVfAnalyticsData.data.fileTypes.labels.map(ext => '.' + ext),
                colors: ['#667eea', '#764ba2', '#f093fb', '#f5576c', '#11998e', '#38ef7d', '#2196f3', '#21cbf3'],
                stroke: {
                    show: false,
                    width: 0
                },
                legend: {
                    position: 'bottom',
                    fontSize: '14px',
                    fontWeight: 500,
                    labels: {
                        colors: '#50575e'
                    },
                    markers: {
                        width: 14,
                        height: 14,
                        radius: 3
                    },
                    itemMargin: {
                        horizontal: 10,
                        vertical: 5
                    }
                },
                plotOptions: {
                    pie: {
                        donut: {
                            size: '50%',
                            labels: {
                                show: true,
                                name: {
                                    fontSize: '16px',
                                    fontWeight: 600,
                                    color: '#1d2327'
                                },
                                value: {
                                    fontSize: '32px',
                                    fontWeight: 700,
                                    color: '#1d2327',
                                    formatter: function(val) {
                                        return val.toLocaleString();
                                    }
                                },
                                total: {
                                    show: true,
                                    label: 'Total Views',
                                    fontSize: '16px',
                                    fontWeight: 600,
                                    color: '#50575e',
                                    formatter: function(w) {
                                        const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                        return total.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                },
                dataLabels: {
                    enabled: true,
                    formatter: function(val, opts) {
                        return val.toFixed(1) + '%';
                    },
                    style: {
                        fontSize: '13px',
                        fontWeight: 600,
                        colors: ['#fff']
                    },
                    dropShadow: {
                        enabled: true,
                        top: 1,
                        left: 1,
                        blur: 1,
                        opacity: 0.45
                    }
                },
                tooltip: {
                    theme: 'dark',
                    y: {
                        formatter: function(val) {
                            return val.toLocaleString() + ' views';
                        }
                    }
                },
                responsive: [{
                    breakpoint: 600,
                    options: {
                        chart: {
                            height: 280
                        },
                        legend: {
                            position: 'bottom'
                        }
                    }
                }]
            };

            this.charts.fileType = new ApexCharts(container, options);
            this.charts.fileType.render();
        },

        /**
         * Render Hourly Views Chart (Bar Chart)
         */
        renderHourlyChart: function() {
            const container = document.getElementById('vf-hourly-chart');
            if (!container || !intentdeepVfAnalyticsData.data.hourlyViews) {
                return;
            }

            const options = {
                chart: {
                    type: 'bar',
                    height: 300,
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',
                    toolbar: {
                        show: false
                    },
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800
                    }
                },
                series: [{
                    name: 'Views',
                    data: intentdeepVfAnalyticsData.data.hourlyViews.data
                }],
                xaxis: {
                    categories: intentdeepVfAnalyticsData.data.hourlyViews.labels.map(hour => {
                        // Format hour: "00" -> "12 AM", "13" -> "1 PM"
                        const h = parseInt(hour);
                        const period = h >= 12 ? 'PM' : 'AM';
                        const displayHour = h === 0 ? 12 : (h > 12 ? h - 12 : h);
                        return displayHour + ' ' + period;
                    }),
                    labels: {
                        rotate: -45,
                        rotateAlways: false,
                        style: {
                            fontSize: '11px',
                            colors: '#50575e'
                        }
                    },
                    axisBorder: {
                        color: '#dcdcde'
                    },
                    axisTicks: {
                        color: '#dcdcde'
                    }
                },
                yaxis: {
                    title: {
                        text: 'Views',
                        style: {
                            fontSize: '12px',
                            fontWeight: 600,
                            color: '#50575e'
                        }
                    },
                    labels: {
                        style: {
                            fontSize: '12px',
                            colors: '#50575e'
                        },
                        formatter: function(val) {
                            return Math.floor(val);
                        }
                    }
                },
                colors: ['#11998e'],
                plotOptions: {
                    bar: {
                        borderRadius: 4,
                        dataLabels: {
                            position: 'top'
                        },
                        distributed: false
                    }
                },
                dataLabels: {
                    enabled: false
                },
                grid: {
                    borderColor: '#f0f0f1',
                    strokeDashArray: 4,
                    xaxis: {
                        lines: {
                            show: false
                        }
                    }
                },
                tooltip: {
                    theme: 'dark',
                    y: {
                        formatter: function(val) {
                            return val + ' views';
                        }
                    }
                }
            };

            this.charts.hourly = new ApexCharts(container, options);
            this.charts.hourly.render();
        },

        /**
         * Initialize event handlers
         */
        initEventHandlers: function() {
            // Date range filter
            $('#vf-date-range').on('change', (e) => {
                this.refreshData($(e.target).val());
            });

            // Refresh button
            $('#vf-refresh-analytics').on('click', () => {
                const days = $('#vf-date-range').val();
                this.refreshData(days);
            });
        },

        /**
         * Refresh analytics data
         */
        refreshData: function(days) {
            const $wrap = $('.vf-analytics-wrap');
            const $button = $('#vf-refresh-analytics');

            // Add loading states
            $wrap.addClass('vf-analytics-loading');
            $button.addClass('loading').prop('disabled', true);

            $.ajax({
                url: intentdeepVfAnalyticsData.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'intentdeep_vf_refresh_analytics',
                    nonce: intentdeepVfAnalyticsData.nonce,
                    days: days
                },
                success: (response) => {
                    if (response.success && response.data) {
                        this.updateCharts(response.data);
                    } else {
                        this.showError(response.data?.message || 'Failed to refresh data');
                    }
                },
                error: () => {
                    this.showError('Network error. Please try again.');
                },
                complete: () => {
                    // Remove loading states
                    $wrap.removeClass('vf-analytics-loading');
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },

        /**
         * Update charts with new data
         */
        updateCharts: function(data) {
            // Update timeline chart
            if (this.charts.timeline && data.timeline) {
                this.charts.timeline.updateOptions({
                    xaxis: {
                        categories: data.timeline.labels.map(date => {
                            const d = new Date(date);
                            return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                        }),
                        labels: {
                            rotate: -45,
                            rotateAlways: true,
                            hideOverlappingLabels: true,
                            trim: false,
                            style: {
                                fontSize: '11px',
                                colors: '#50575e'
                            }
                        }
                    }
                });
                this.charts.timeline.updateSeries([{
                    data: data.timeline.data
                }]);
            }

            // Update top files table
            if (data.topFiles) {
                this.updateTopFilesTable(data.topFiles);
            }
        },

        /**
         * Update top files table
         */
        updateTopFilesTable: function(files) {
            const $tbody = $('#vf-top-files-tbody');

            if (!files || files.length === 0) {
                $tbody.html('<tr><td colspan="4" class="vf-no-data">No data available for the selected period.</td></tr>');
                return;
            }

            let html = '';
            files.forEach((file, index) => {
                const rankClass = index < 3 ? `vf-rank-${index + 1}` : '';
                const editUrl = intentdeepVfAnalyticsData.ajaxUrl.replace('admin-ajax.php', 'post.php?post=' + file.id + '&action=edit');

                let lastAccessed = 'Never';
                if (file.last_accessed) {
                    const now = Math.floor(Date.now() / 1000);
                    const then = Math.floor(new Date(file.last_accessed).getTime() / 1000);
                    const diff = now - then;

                    if (diff < 60) lastAccessed = diff + ' seconds ago';
                    else if (diff < 3600) lastAccessed = Math.floor(diff / 60) + ' minutes ago';
                    else if (diff < 86400) lastAccessed = Math.floor(diff / 3600) + ' hours ago';
                    else lastAccessed = Math.floor(diff / 86400) + ' days ago';
                }

                html += `
                    <tr>
                        <td class="vf-rank">
                            <span class="vf-rank-badge ${rankClass}">#${index + 1}</span>
                        </td>
                        <td class="vf-filename">
                            <a href="${editUrl}">${file.filename}</a>
                            <div class="vf-file-meta">
                                <span class="vf-mime-type">${file.mime_type || 'unknown'}</span>
                            </div>
                        </td>
                        <td class="vf-views">
                            <strong>${file.views.toLocaleString()}</strong>
                        </td>
                        <td class="vf-last-accessed">${lastAccessed}</td>
                    </tr>
                `;
            });

            $tbody.html(html);
        },

        /**
         * Show error message
         */
        showError: function(message) {
            // Could implement a toast notification here
            console.error('Analytics Error:', message);
            alert('Error: ' + message);
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        VFAnalytics.init();
    });

})(jQuery);
