<script setup lang="ts">
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import type { WatchSparkPoint } from '@/composables/useWatchPins'

use([CanvasRenderer, LineChart, GridComponent, TooltipComponent])

const props = defineProps<{
  points: WatchSparkPoint[]
  metric?: 'cpu_pct' | 'mem_pct' | 'disk_pct' | 'net_down_bps'
  height?: number
}>()

const metricKey = computed(() => props.metric || 'cpu_pct')

const chartOption = computed(() => {
  const key = metricKey.value
  const xs = props.points.map((p) => p.ts || '')
  const ys = props.points.map((p) => (p[key] ?? null) as number | null)
  return {
    animation: false,
    grid: { left: 4, right: 4, top: 4, bottom: 4 },
    xAxis: { type: 'category', show: false, data: xs },
    yAxis: { type: 'value', show: false, min: 0 },
    tooltip: { trigger: 'axis', confine: true },
    series: [{
      type: 'line',
      data: ys,
      showSymbol: false,
      smooth: true,
      lineStyle: { width: 1.5 },
      areaStyle: { opacity: 0.08 },
    }],
  }
})
</script>

<template>
  <v-chart
    class="watch-sparkline"
    :style="{ height: `${height ?? 48}px` }"
    :option="chartOption"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>

<style scoped>
.watch-sparkline {
  width: 100%;
  pointer-events: none;
}
</style>
