let charts = {};

document.addEventListener('DOMContentLoaded', function() {
    const overviewTabButton = document.querySelector('[data-tab="overview"]');
    const statisticsTabButton = document.querySelector('[data-tab="statistics"]');
    
    overviewTabButton.addEventListener('click', function() {
        setTimeout(() => {
            initializeOverviewCharts();
        }, 100);
    });
    
    statisticsTabButton.addEventListener('click', function() {
        setTimeout(() => {
            initializeStatisticsCharts();
        }, 100);
    });
    
    if (window.appData.charts) {
        initializeOverviewCharts();
        initializeStatisticsCharts();
        initializeDetailedStats();
    }
});

function initializeOverviewCharts() {
    const chartData = window.appData.charts;
    
    if (!chartData) return;
    
    destroyChart('priority-chart');
    destroyChart('constraint-chart');
    
    const priorityCtx = document.getElementById('priority-chart');
    const constraintCtx = document.getElementById('constraint-chart');
    
    if (priorityCtx && chartData.priority_distribution) {
        charts['priority-chart'] = new Chart(priorityCtx, {
            type: 'pie',
            data: {
                labels: chartData.priority_distribution.labels,
                datasets: [{
                    data: chartData.priority_distribution.data,
                    backgroundColor: [
                        '#ef4444',
                        '#f59e0b',
                        '#10b981',
                        '#3b82f6'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            color: '#e0e0e0',
                            padding: 15
                        }
                    }
                }
            }
        });
    }
    
    if (constraintCtx && chartData.constraint_distribution) {
        charts['constraint-chart'] = new Chart(constraintCtx, {
            type: 'doughnut',
            data: {
                labels: chartData.constraint_distribution.labels,
                datasets: [{
                    data: chartData.constraint_distribution.data,
                    backgroundColor: [
                        '#ef4444',
                        '#10b981'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            color: '#e0e0e0',
                            padding: 15
                        }
                    }
                }
            }
        });
    }
}

function initializeStatisticsCharts() {
    const chartData = window.appData.charts;
    
    if (!chartData) return;
    
    destroyChart('categories-chart');
    destroyChart('sentence-chart');
    
    const categoriesCtx = document.getElementById('categories-chart');
    const sentenceCtx = document.getElementById('sentence-chart');
    
    if (categoriesCtx && chartData.variable_categories && chartData.variable_categories.labels.length > 0) {
        charts['categories-chart'] = new Chart(categoriesCtx, {
            type: 'bar',
            data: {
                labels: chartData.variable_categories.labels,
                datasets: [{
                    label: 'Variables by Category',
                    data: chartData.variable_categories.data,
                    backgroundColor: [
                        '#3b82f6',
                        '#10b981',
                        '#f59e0b',
                        '#ef4444',
                        '#8b5cf6',
                        '#ec4899'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                indexAxis: 'y',
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            color: '#a0a0a0'
                        },
                        grid: {
                            color: '#333333'
                        }
                    },
                    y: {
                        ticks: {
                            color: '#a0a0a0'
                        },
                        grid: {
                            color: '#333333'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
    
    if (sentenceCtx && chartData.sentence_length_distribution) {
        const sentenceData = chartData.sentence_length_distribution;
        
        charts['sentence-chart'] = new Chart(sentenceCtx, {
            type: 'bar',
            data: {
                labels: ['Min', 'Mean', 'Median', 'Max'],
                datasets: [{
                    label: 'Sentence Length',
                    data: [
                        sentenceData.min,
                        sentenceData.mean,
                        sentenceData.median,
                        sentenceData.max
                    ],
                    backgroundColor: '#3b82f6',
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    x: {
                        ticks: {
                            color: '#a0a0a0'
                        },
                        grid: {
                            color: '#333333'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: '#a0a0a0'
                        },
                        grid: {
                            color: '#333333'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
}

function initializeDetailedStats() {
    const chartData = window.appData.charts;
    const container = document.getElementById('detailed-stats');
    
    if (!chartData || !chartData.sentence_length_distribution) {
        return;
    }
    
    const sentenceStats = chartData.sentence_length_distribution;
    
    const statsData = [
        { label: 'Min Sentence Length', value: sentenceStats.min },
        { label: 'Max Sentence Length', value: sentenceStats.max },
        { label: 'Mean Sentence Length', value: sentenceStats.mean.toFixed(1) },
        { label: 'Median Sentence Length', value: sentenceStats.median.toFixed(1) }
    ];
    
    container.innerHTML = statsData.map(stat => `
        <div class="stat-card">
            <div class="value">${stat.value}</div>
            <div class="label">${stat.label}</div>
        </div>
    `).join('');
}

function destroyChart(chartId) {
    if (charts[chartId]) {
        charts[chartId].destroy();
        delete charts[chartId];
    }
}

window.addEventListener('resize', function() {
    if (currentTab === 'overview') {
        initializeOverviewCharts();
    } else if (currentTab === 'statistics') {
        initializeStatisticsCharts();
    }
});
