// Bar-chart helper used by PerformanceDetail.razor. Wraps Chart.js so the Razor side just
// passes labels + values; we own the colors and the lifecycle.
//
// One chart per canvas id. Re-calling render() destroys the previous chart so the date-range
// filter on the detail page can refresh without leaking instances.
window.tmPerfChart = window.tmPerfChart || (function () {
    const charts = new Map();

    function brandColor() {
        // Match the app's brand purple so the bar chart blends with the rest of the UI.
        return getComputedStyle(document.documentElement).getPropertyValue('--tm-brand').trim() || '#6366f1';
    }

    function dispose(id) {
        const prior = charts.get(id);
        if (prior) {
            try { prior.destroy(); } catch { }
            charts.delete(id);
        }
    }

    function render(id, labels, values) {
        if (typeof Chart === 'undefined') return; // CDN not loaded yet
        const canvas = document.getElementById(id);
        if (!canvas) return;
        dispose(id);

        const chart = new Chart(canvas.getContext('2d'), {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Completed',
                    data: values,
                    backgroundColor: brandColor(),
                    borderRadius: 6,
                    maxBarThickness: 36
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return ctx.parsed.y + ' completed';
                            }
                        }
                    }
                },
                scales: {
                    y: { beginAtZero: true, ticks: { precision: 0 } },
                    x: { grid: { display: false } }
                }
            }
        });
        charts.set(id, chart);
    }

    return { render, dispose };
})();
