<script>
    import { onDestroy, onMount } from "svelte";
    import { Chart } from "chart.js/auto";

    let { chartData, typec = "bar" } = $props();

    let chartContainer;
    let instance;

    onDestroy(() => {
        if (instance) {
            instance.destroy();
        }
    });

    const createChart = () => {
        if (instance) {
            instance.destroy();
        }

        const ctx = chartContainer.getContext("2d");
        instance = new Chart(ctx, {
            type: typec,
            data: {
                labels: chartData.labels,
                datasets: chartData.datasets.map((dataset) => ({
                    label: dataset.label,
                    data: dataset.data.map((x) => String(x)),
                    borderWidth: dataset.borderWidth,
                })),
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: "top",
                    },
                },
                scales: {
                    x: {
                        beginAtZero: true,
                    },
                    y: {
                        beginAtZero: true,
                    },
                },
            },
        });
    };
    onMount(createChart);
    $effect(createChart);
</script>

<div class="card card-body">
    <canvas bind:this={chartContainer}></canvas>
</div>
