<script setup>
import { computed, toValue, shallowRef, markRaw } from 'vue'
import { Line } from 'vue-chartjs'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

const props = defineProps({
  chartData: { type: Object, required: true },
  title: { type: String, required: true },
  yMin: { type: Number, default: undefined },
  yMax: { type: Number, default: undefined },
})

const lineData = computed(() => {
  const data = toValue(props.chartData)
  return data?.datasets ? data : { labels: [], datasets: [] }
})

const chartOptions = shallowRef(markRaw({
  responsive: true,
  maintainAspectRatio: true,
  animation: {
    duration: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400,
  },
  scales: {
    y: { min: props.yMin, max: props.yMax },
    x: { ticks: { maxTicksAuto: true, maxRotation: 45 } },
  },
  plugins: {
    legend: { display: false },
  },
}))
</script>

<template>
  <div class="w-full min-w-0 rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-900">
    <h3 class="mb-4 text-sm font-medium text-gray-700 dark:text-gray-300">{{ title }}</h3>
    <div class="aspect-video w-full min-h-0 overflow-hidden">
      <Line :data="lineData" :options="chartOptions" />
    </div>
  </div>
</template>