document.addEventListener("DOMContentLoaded", function () {
    console.log("Cargando: charts.js");

    const languageLabels = JSON.parse(document.getElementById("language-data").textContent);
    const textCounts = JSON.parse(document.getElementById("text-counts").textContent);
    const fileCounts = JSON.parse(document.getElementById("file-counts").textContent);
    const mediaCounts = JSON.parse(document.getElementById("media-counts").textContent);

    const ctx = document.getElementById('languageTypeChart').getContext('2d');

    // Crear gráfico y asignarlo a window para acceso global
    window.languageTypeChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: languageLabels,
            datasets: [
                { label: 'Text Pastes', data: textCounts, backgroundColor: '#4E79A7' },
                { label: 'File Pastes', data: fileCounts, backgroundColor: '#F28E2C' },
                { label: 'Media Pastes', data: mediaCounts, backgroundColor: '#E15759' }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'top', labels: { font: { size: 10 } } }
            },
            scales: {
                x: { stacked: true, ticks: { font: { size: 10 } } },
                y: { stacked: true, beginAtZero: true, ticks: { font: { size: 10 } } }
            }
        }
    });

    // Definir función para actualizar dinámicamente el gráfico
    window.updateCharts = function(stats) {
        const chart = window.languageTypeChart;
        chart.data.labels = stats.languageLabels;
        chart.data.datasets[0].data = stats.textCounts;
        chart.data.datasets[1].data = stats.fileCounts;
        chart.data.datasets[2].data = stats.mediaCounts;
        chart.update();
    };
});
