<script lang="ts">
	import { onMount } from "svelte";
	import type { Chart as ChartType, ChartOptions } from "chart.js";

	let {
		data = [],
		index = "name",
		categories = ["value"],
		colors = ["primary"],
		valueFormatter = (value: any) => value.toString(),
		showLegend = true,
	}: {
		data: any[];
		index?: string;
		categories?: string[];
		colors?: string[];
		valueFormatter?: (value: any) => string;
		showLegend?: boolean;
	} = $props();

	let chartElement: HTMLCanvasElement | undefined = $state(undefined);
	let chart: ChartType | undefined = $state(undefined);

	const colorMap: Record<string, string> = {
		primary: "#7e67e6",
		blue: "#3b82f6",
		green: "#22c55e",
		emerald: "#10b981",
		rose: "#f43f5e",
		amber: "#f59e0b",
	};

	onMount(() => {
		if (typeof window !== "undefined" && data.length > 0) {
			// Modern ES Module import with explicit imports
			Promise.all([import("chart.js/auto"), import("chart.js")]).then(
				([
					ChartModule,
					{
						Chart,
						BarController,
						CategoryScale,
						LinearScale,
						BarElement,
						Title,
						Tooltip,
						Legend,
					},
				]) => {
					// Register only what we need
					Chart.register(
						BarController,
						CategoryScale,
						LinearScale,
						BarElement,
						Title,
						Tooltip,
						Legend,
					);

					if (chartElement) {
						const labels = data.map((item) => item[index]);
						const datasets = categories.map((category, i) => ({
							label: category,
							data: data.map((item) => item[category] || 0),
							backgroundColor: colorMap[colors[i % colors.length]],
							borderRadius: 4,
						}));

						chart = new Chart(chartElement, {
							type: "bar",
							data: {
								labels,
								datasets,
							},
							options: {
								responsive: true,
								maintainAspectRatio: false,
								plugins: {
									legend: {
										display: showLegend,
										position: "top",
									},
									tooltip: {
										callbacks: {
											label: function (context) {
												return valueFormatter(
													context.raw,
												);
											},
										},
									},
								},
								scales: {
									y: {
										beginAtZero: true,
										ticks: {
											callback: function (value) {
												return value;
											},
										},
									},
								},
							} as ChartOptions,
						});
					}
				},
			);
		}

		return () => {
			if (chart) {
				chart.destroy();
			}
		};
	});

	$effect(() => {
		if (chart && data.length > 0) {
			chart.data.labels = data.map((item) => item[index]);
			categories.forEach((category, i) => {
				if (chart?.data?.datasets?.[i]) {
					chart.data.datasets[i].data = data.map(
						(item) => item[category] || 0,
					);
				}
			});
			chart.update();
		}
	});
</script>

<div class="h-[300px] w-full">
	<canvas bind:this={chartElement}></canvas>
</div>
