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

Chart.register(...registerables)

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

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 = computed(() => {
  darkMode.value
  return buildOptions({
    scales: {
      y: { min: 0, max: 20, title: { display: true, text: 'NEWS2 Score' } },
    },
  }).value
})
</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-[220px] min-w-0 overflow-hidden sm:min-h-0"
      role="img"
      aria-label="NEWS2 score over time line chart"
    >
      <Line :data="chartData" :options="chartOptions" />
    </div>
  </div>
</template>
