(() => {
    const node = document.getElementById('analytics-data');
    if (!node || typeof Chart === 'undefined') {
        return;
    }

    let payload;
    try {
        payload = JSON.parse(node.textContent || '{}');
    } catch (error) {
        return;
    }

    const doughnut = (canvasId, chart) => {
        if (!chart || chart.empty) {
            return;
        }
        const canvas = document.getElementById(canvasId);
        if (!canvas) {
            return;
        }
        const counts = Array.isArray(chart.counts) ? chart.counts : [];
        const total = counts.reduce((sum, value) => sum + Number(value || 0), 0);
        if (total <= 0) {
            return;
        }

        new Chart(canvas, {
            type: 'doughnut',
            data: {
                labels: Array.isArray(chart.labels) ? chart.labels : [],
                datasets: [{
                    data: counts,
                    backgroundColor: Array.isArray(chart.colors) ? chart.colors : [],
                    borderWidth: 0,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: false },
                },
                cutout: '58%',
            },
        });
    };

    doughnut('analytics-status-chart', payload.status);
    doughnut('analytics-priority-chart', payload.priority);
    doughnut('analytics-category-chart', payload.category);
})();
