<script setup>
import { computed, shallowRef, markRaw } from 'vue'
import { Line } from 'vue-chartjs'
import { Chart, registerables } from 'chart.js'
import { formatTime } from '@/composables/chartFormat'

Chart.register(...registerables)

const props = defineProps({ history: { type: Array, required: true } })

const chartData = computed(() => ({
  labels: props.history.map(h => formatTime(h.calculatedAt)),
  datasets: [{
    label: 'NEWS2',
    data: props.history.map(h => h.totalScore),
    borderColor: '#3b82f6',
    backgroundColor: props.history.map(h => {
      if (h.totalScore >= 7) return 'rgba(220, 38, 38, 0.3)'
      if (h.totalScore >= 5) return 'rgba(245, 158, 11, 0.3)'
      return 'rgba(34, 197, 94, 0.3)'
    }),
    fill: true,
    tension: 0.3,
    pointRadius: 4,
  }],
}))

const chartOptions = shallowRef(markRaw({
  responsive: true,
  maintainAspectRatio: true,
  animation: {
    duration: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400,
  },
  scales: {
    y: { min: 0, max: 20, title: { display: true, text: 'NEWS2 Score' } },
  },
  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">NEWS2 Score Over Time</h3>
    <div class="aspect-video w-full min-h-0 overflow-hidden">
      <Line :data="chartData" :options="chartOptions" />
    </div>
  </div>
</template>
