// DashboardHelpers/ChartRenderer.js


export default class ChartRenderer {
    // Google Search Console style - light blue line
    static colorMap = {
        'sessions': '#4285f4',
        'visits': '#4285f4',
        'views': '#4285f4',
        'bounce_rate': '#4285f4',
        'comparison': '#bdbdbd',
        'comparisonHighlight': '#ff9800'
    };
    constructor(colorMapOverride = null) {
        this.chart = null; // Chart.js instance
        this.colorMap = colorMapOverride || ChartRenderer.colorMap;
    }

    // Chart.js implementation
    renderAmChart({ chartDivId, data, comparisonData, metric, getMetricDisplayName }) {
        
        // Dispose previous chart if it exists
        this.disposeAmChart();

        let chartDiv = document.getElementById(chartDivId);
        if (!chartDiv) {
            console.error('ChartRenderer: Chart div not found:', chartDivId);
            return;
        }
        
        // Check if Chart.js is loaded (try multiple ways to access it)
        let ChartLib = typeof Chart !== 'undefined' ? Chart : 
                      (typeof window !== 'undefined' && typeof window.Chart !== 'undefined') ? window.Chart :
                      (typeof globalThis !== 'undefined' && typeof globalThis.Chart !== 'undefined') ? globalThis.Chart :
                      null;
        
        if (!ChartLib) {
            console.error('ChartRenderer: Chart.js library not loaded');
            // Show error message to user
            const statusMessage = document.getElementById('sentinelpro-status-message');
            if (statusMessage) {
                statusMessage.textContent = 'Chart library failed to load. Please refresh the page.';
                statusMessage.style.display = 'block';
                statusMessage.style.color = '#d63638';
            }
            return;
        }
        
        // Clear any previous error messages
        const statusMessage = document.getElementById('sentinelpro-status-message');
        if (statusMessage) {
            statusMessage.textContent = '';
            statusMessage.style.display = 'none';
        }
        
        // Check if we have data to display
        const hasData = data && Array.isArray(data) && data.length > 0;
        const hasComparisonData = comparisonData && Array.isArray(comparisonData) && comparisonData.length > 0;
        
        if (!hasData && !hasComparisonData) {
            console.warn('ChartRenderer: No data to display');
            chartDiv.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#666;font-size:14px;">No data available for the selected date range</div>';
            return;
        }
        
        // Create canvas if it doesn't exist
        let canvas = chartDiv.querySelector('canvas');
        if (!canvas) {
            canvas = document.createElement('canvas');
            chartDiv.innerHTML = '';
            chartDiv.appendChild(canvas);
        }
        
        const ctx = canvas.getContext('2d');
        
        // Prepare datasets
        const datasets = [];
        
        // Main data series - Google Search Console style
        if (hasData) {
            datasets.push({
                label: getMetricDisplayName(metric) + (hasComparisonData ? ' (Current)' : ''),
                data: data.map(row => ({
                    x: row.date,
                    y: row[metric] || 0
                })),
                borderColor: this.colorMap[metric] || '#4285f4',
                backgroundColor: 'transparent',
                borderWidth: 2,
                fill: false,
                tension: 0.3,
                pointRadius: 0,
                pointHoverRadius: 4,
                pointHoverBackgroundColor: this.colorMap[metric] || '#4285f4',
                pointHoverBorderColor: '#fff',
                pointHoverBorderWidth: 2
            });
        }

        // Comparison data series
        if (hasComparisonData) {
            datasets.push({
                label: getMetricDisplayName(metric) + ' (Comparison)',
                data: comparisonData.map(row => ({
                    x: row.date,
                    y: row[metric] || 0
                })),
                borderColor: this.colorMap.comparisonHighlight || '#ff9800',
                backgroundColor: 'transparent',
                borderWidth: 2,
                borderDash: [5, 5],
                fill: false,
                tension: 0.3,
                pointRadius: 0,
                pointHoverRadius: 4,
                pointHoverBackgroundColor: this.colorMap.comparisonHighlight || '#ff9800',
                pointHoverBorderColor: '#fff',
                pointHoverBorderWidth: 2
            });
        }
        
        // Register Chart.js date adapter if available
        if (ChartLib && ChartLib.register && typeof ChartLib._adapters !== 'undefined') {
            // Date adapter should be auto-registered, but ensure it's available
            try {
                // Chart.js with date-fns adapter should be available
            } catch (e) {
                console.warn('ChartRenderer: Date adapter may not be registered');
            }
        }
        
        // Create Chart.js instance - Google Search Console style
        this.chart = new ChartLib(ctx, {
            type: 'line',
            data: {
                datasets: datasets
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        display: false // Hide legend for cleaner look like GSC
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: '#fff',
                        titleColor: '#333',
                        bodyColor: '#666',
                        borderColor: '#e0e0e0',
                        borderWidth: 1,
                        cornerRadius: 4,
                        padding: 10,
                        displayColors: false,
                        callbacks: {
                            title: function(context) {
                                const date = new Date(context[0].parsed.x);
                                return date.toLocaleDateString('en-US', {
                                    month: 'short',
                                    day: 'numeric',
                                    year: 'numeric'
                                });
                            },
                            label: function(context) {
                                const value = context.parsed.y;
                                // Format with K for thousands
                                if (value >= 1000) {
                                    return (value / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
                                }
                                return value.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        type: 'time',
                        time: {
                            unit: 'day',
                            displayFormats: {
                                day: 'M/d/yy'
                            }
                        },
                        grid: {
                            display: false
                        },
                        border: {
                            display: false
                        },
                        ticks: {
                            color: '#5f6368',
                            font: {
                                size: 11,
                                family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif'
                            },
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 12
                        }
                    },
                    y: {
                        beginAtZero: true,
                        position: 'left',
                        grid: {
                            color: '#f0f0f0',
                            drawBorder: false,
                            lineWidth: 1
                        },
                        border: {
                            display: false
                        },
                        ticks: {
                            color: '#5f6368',
                            font: {
                                size: 11,
                                family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif'
                            },
                            padding: 8,
                            callback: function(value) {
                                // Format with K for thousands
                                if (value >= 1000) {
                                    return (value / 1000).toFixed(0) + 'K';
                                }
                                return value;
                            }
                        }
                    }
                },
                layout: {
                    padding: {
                        top: 20,
                        right: 20,
                        bottom: 10,
                        left: 10
                    }
                }
            }
        });
    }

    disposeAmChart() {
        if (this.chart && typeof this.chart.destroy === 'function') {
            this.chart.destroy();
            this.chart = null;
        }
    }

    async exportChartToPDF(chartDivId) {
        // Dynamically load jsPDF and html2canvas if not present
        function loadScript(src) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = src;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }
        if (typeof html2canvas === 'undefined') {
            await loadScript('https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js');
        }
        if (typeof window.jspdf === 'undefined' && typeof jsPDF === 'undefined') {
            await loadScript('https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js');
        }
        const chartDiv = document.getElementById(chartDivId);
        if (!chartDiv) {
            alert('Chart not found!');
            return;
        }
        const canvasImage = await html2canvas(chartDiv, {backgroundColor: '#fff'});
        const imgData = canvasImage.toDataURL('image/png');
        const PDFClass = window.jspdf?.jsPDF || window.jsPDF;
        if (!PDFClass) {
            alert('jsPDF not loaded!');
            return;
        }
        // Scale to A4 landscape (842pt wide)
        const pageWidth = 842;
        const scale = pageWidth / canvasImage.width;
        const pageHeight = canvasImage.height * scale;
        const pdf = new PDFClass({
            orientation: 'landscape',
            unit: 'pt',
            format: [pageWidth, pageHeight]
        });
        pdf.addImage(imgData, 'PNG', 0, 0, pageWidth, pageHeight);
        pdf.save('chart.pdf');
    }

    async exportChartAndTableToPDF(chartDivId, tableId, tableHeaderSelector) {
        function loadScript(src) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = src;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }
        if (typeof html2canvas === 'undefined') {
            await loadScript('https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js');
        }
        if (typeof window.jspdf === 'undefined' && typeof jsPDF === 'undefined') {
            await loadScript('https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js');
        }
        const chartDiv = document.getElementById(chartDivId);
        const table = document.getElementById(tableId);
        const tableHeader = document.querySelector(tableHeaderSelector);
        if (!chartDiv || !table) {
            alert('Chart or table not found!');
            return;
        }
        const tempWrapper = document.createElement('div');
        if (tableHeader) {
            tempWrapper.appendChild(tableHeader.cloneNode(true));
        }
        tempWrapper.appendChild(table.cloneNode(true));
        tempWrapper.style.background = '#fff';
        tempWrapper.style.padding = '16px';
        tempWrapper.style.width = table.offsetWidth + 'px';
        document.body.appendChild(tempWrapper);
        const chartCanvas = await html2canvas(chartDiv, {backgroundColor: '#fff'});
        const tableCanvas = await html2canvas(tempWrapper, {backgroundColor: '#fff'});
        const chartImg = chartCanvas.toDataURL('image/png');
        const tableImg = tableCanvas.toDataURL('image/png');
        document.body.removeChild(tempWrapper);
        const PDFClass = window.jspdf?.jsPDF || window.jsPDF;
        if (!PDFClass) {
            alert('jsPDF not loaded!');
            return;
        }
        // Scale to A4 landscape (842pt wide)
        const pageWidth = 842;
        const chartScale = pageWidth / chartCanvas.width;
        const tableScale = pageWidth / tableCanvas.width;
        const chartHeight = chartCanvas.height * chartScale;
        const tableHeight = tableCanvas.height * tableScale;
        const pdfHeight = chartHeight + tableHeight;
        const pdf = new PDFClass({
            orientation: 'landscape',
            unit: 'pt',
            format: [pageWidth, pdfHeight]
        });
        pdf.addImage(chartImg, 'PNG', 0, 0, pageWidth, chartHeight);
        pdf.addImage(tableImg, 'PNG', 0, chartHeight, pageWidth, tableHeight);
        pdf.save('chart-table.pdf');
    }
}