/**
 * SEO Analytics Dashboard JavaScript
 * Handles data loading, chart rendering, and user interactions
 */

class SEODashboard {
    constructor() {
        this.charts = {};
        this.refreshInterval = 300000; // 5 minutes
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.loadDashboardData();
        this.setupAutoRefresh();
    }

    setupEventListeners() {
        const refreshBtn = document.getElementById('refresh-data');
        const exportBtn = document.getElementById('export-report');

        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => this.loadDashboardData());
        }

        if (exportBtn) {
            exportBtn.addEventListener('click', () => this.exportReport());
        }
    }

    loadDashboardData() {
        console.log('Loading dashboard data...');
        this.showLoading();

        Promise.all([
            this.loadSearchPerformance(),
            this.loadRealtimeData(),
            this.loadTopPages(),
            this.loadTrafficTrends(),
        ]).then(() => {
            this.hideLoading();
            console.log('Dashboard data loaded');
        }).catch(error => {
            console.error('Error loading dashboard:', error);
            this.showError('Failed to load dashboard data');
            this.hideLoading();
        });
    }

    async loadSearchPerformance() {
        try {
            const response = await fetch('/api/seo_analytics/search_performance.php?days=30');
            const data = await response.json();

            if (data.status === 'success' && data.data.length > 0) {
                this.updateSearchMetrics(data.data);
                this.renderSearchChart(data.data);
            }
        } catch (error) {
            console.error('Error loading search performance:', error);
        }
    }

    async loadRealtimeData() {
        try {
            const response = await fetch('/api/seo_analytics/realtime_users.php');
            const data = await response.json();

            if (data.status === 'success') {
                this.renderRealtimeChart(data.data);
            }
        } catch (error) {
            console.error('Error loading realtime data:', error);
        }
    }

    async loadTopPages() {
        try {
            const response = await fetch('/api/seo_analytics/top_pages.php?days=30');
            const data = await response.json();

            if (data.status === 'success') {
                this.renderTopPages(data.data);
            }
        } catch (error) {
            console.error('Error loading top pages:', error);
        }
    }

    async loadTrafficTrends() {
        try {
            const response = await fetch('/api/seo_analytics/traffic_trends.php?hours=24');
            const data = await response.json();

            if (data.status === 'success') {
                this.renderTrafficChart(data.data);
            }
        } catch (error) {
            console.error('Error loading traffic trends:', error);
        }
    }

    updateSearchMetrics(data) {
        let totalClicks = 0, totalImpressions = 0, ctrSum = 0, positionSum = 0;

        data.forEach(row => {
            totalClicks += parseInt(row.clicks) || 0;
            totalImpressions += parseInt(row.impressions) || 0;
            ctrSum += parseFloat(row.ctr) || 0;
            positionSum += parseFloat(row.position) || 0;
        });

        const avgCTR = ((ctrSum / data.length) || 0).toFixed(2);
        const avgPosition = ((positionSum / data.length) || 0).toFixed(1);

        this.updateElement('total-clicks', totalClicks.toLocaleString());
        this.updateElement('total-impressions', totalImpressions.toLocaleString());
        this.updateElement('avg-ctr', avgCTR + '%');
        this.updateElement('avg-position', avgPosition);
    }

    renderSearchChart(data) {
        const container = document.getElementById('performance-chart');
        if (!container) return;

        // Sort data by position (top performing queries first)
        const sorted = data.slice(0, 10).sort((a, b) => 
            parseInt(b.clicks) - parseInt(a.clicks)
        );

        const options = {
            chart: {
                type: 'bar',
                height: 300,
                toolbar: { show: false }
            },
            series: [{
                name: 'Clicks',
                data: sorted.map(d => parseInt(d.clicks) || 0)
            }],
            xaxis: {
                categories: sorted.map(d => d.query.substring(0, 20))
            },
            colors: ['#667eea'],
            dataLabels: {
                enabled: false
            }
        };

        // Destroy existing chart if it exists
        if (this.charts.searchPerformance) {
            this.charts.searchPerformance.destroy();
        }

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

    renderRealtimeChart(data) {
        const container = document.getElementById('realtime-chart');
        if (!container || !data.by_device) return;

        const options = {
            chart: {
                type: 'pie',
                height: 300
            },
            series: Object.values(data.by_device),
            labels: Object.keys(data.by_device).map(device => 
                device.charAt(0).toUpperCase() + device.slice(1)
            ),
            colors: ['#667eea', '#764ba2', '#f093fb'],
            responsive: [{
                breakpoint: 480,
                options: {
                    chart: { height: 300 },
                    legend: { position: 'bottom' }
                }
            }]
        };

        if (this.charts.realtime) {
            this.charts.realtime.destroy();
        }

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

    renderTrafficChart(data) {
        const container = document.getElementById('traffic-chart');
        if (!container || !data || data.length === 0) return;

        const options = {
            chart: {
                type: 'line',
                height: 300,
                toolbar: { show: false }
            },
            series: [{
                name: 'Active Users',
                data: data.map(d => d.active_users)
            }],
            xaxis: {
                categories: data.map(d => this.formatTime(d.timestamp))
            },
            stroke: {
                curve: 'smooth',
                width: 2
            },
            colors: ['#667eea']
        };

        if (this.charts.traffic) {
            this.charts.traffic.destroy();
        }

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

    renderTopPages(data) {
        const tbody = document.getElementById('top-pages-body');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (!data || data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-center">No data available</td></tr>';
            return;
        }

        data.slice(0, 10).forEach(page => {
            tbody.innerHTML += `
                <tr>
                    <td><a href="${page.page}" target="_blank" class="link">${page.page}</a></td>
                    <td>${parseInt(page.pageviews).toLocaleString()}</td>
                    <td>${parseInt(page.sessions).toLocaleString()}</td>
                    <td>${page.engagement_rate}</td>
                </tr>
            `;
        });
    }

    updateElement(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    formatTime(timestamp) {
        if (!timestamp) return '';
        // Format timestamp for display
        return timestamp.substring(8, 10) + ':' + timestamp.substring(10, 12);
    }

    showLoading() {
        document.body.classList.add('loading');
    }

    hideLoading() {
        document.body.classList.remove('loading');
    }

    showError(message) {
        const alert = document.createElement('div');
        alert.className = 'alert alert-error';
        alert.textContent = message;
        alert.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999;';
        document.body.appendChild(alert);

        setTimeout(() => alert.remove(), 5000);
    }

    setupAutoRefresh() {
        setInterval(() => {
            this.loadDashboardData();
        }, this.refreshInterval);
    }

    exportReport() {
        console.log('Exporting report...');
        // Generate CSV export
        const csv = this.generateCSV();
        this.downloadCSV(csv, 'seo_report_' + new Date().toISOString().split('T')[0] + '.csv');
    }

    generateCSV() {
        let csv = 'SEO Analytics Report\n';
        csv += 'Generated: ' + new Date().toLocaleString() + '\n\n';

        // Add metrics
        csv += 'METRICS\n';
        csv += 'Total Clicks,' + document.getElementById('total-clicks')?.textContent || 'N/A' + '\n';
        csv += 'Total Impressions,' + document.getElementById('total-impressions')?.textContent || 'N/A' + '\n';
        csv += 'Avg CTR,' + document.getElementById('avg-ctr')?.textContent || 'N/A' + '\n';
        csv += 'Avg Position,' + document.getElementById('avg-position')?.textContent || 'N/A' + '\n';

        return csv;
    }

    downloadCSV(csv, filename) {
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);

        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// Initialize dashboard when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.seoDashboard = new SEODashboard();
    });
} else {
    window.seoDashboard = new SEODashboard();
}
