<template>
  <div class="server-metric-sparklines">
    <div class="d-flex align-center justify-space-between mb-2">
      <span class="text-caption text-medium-emphasis">
        24h 趋势（每 {{ intervalMinutes }} 分钟采样）
      </span>
      <v-btn
        v-if="error"
        variant="text"
        size="x-small"
        color="primary"
        @click="$emit('retry')"
      >
        重试
      </v-btn>
    </div>

    <v-skeleton-loader v-if="loading" type="image" height="120" class="rounded mb-2" />

    <div v-else-if="error" class="text-caption text-error py-1 mb-2">{{ error }}</div>

    <div v-else-if="!hasPoints" class="text-caption text-medium-emphasis py-1 mb-2">
      暂无历史数据（部署后约 10 分钟起陆续有采样）
    </div>

    <template v-else>
      <v-row dense>
        <v-col cols="12" md="6">
          <div class="d-flex justify-space-between text-caption mb-1">
            <span class="text-medium-emphasis">CPU</span>
            <span>{{ latestCpu }}</span>
          </div>
          <v-sparkline
            :model-value="cpuSeries"
            :labels="sparklineLabels"
            color="primary"
            height="48"
            smooth
            interactive
            auto-draw
          />
        </v-col>
        <v-col cols="12" md="6">
          <div class="d-flex justify-space-between text-caption mb-1">
            <span class="text-medium-emphasis">内存</span>
            <span>{{ latestMem }}</span>
          </div>
          <v-sparkline
            :model-value="memSeries"
            :labels="sparklineLabels"
            color="secondary"
            height="48"
            smooth
            interactive
            auto-draw
          />
        </v-col>
      </v-row>

      <div v-if="offlineSegments.length" class="d-flex flex-wrap ga-1 mt-2">
        <v-chip
          v-for="(seg, i) in offlineSegments"
          :key="`${seg.from}-${seg.to}-${i}`"
          size="x-small"
          variant="tonal"
          color="grey"
          label
        >
          离线 {{ formatSegment(seg) }}
        </v-chip>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { ServerMetricOfflineSegment, ServerMetricPoint } from '@/types/api'
import { formatPointTimeBeijing } from '@/utils/fleetTrendAnalytics'

const props = defineProps<{
  points: ServerMetricPoint[]
  offlineSegments: ServerMetricOfflineSegment[]
  intervalMinutes: number
  loading?: boolean
  error?: string
}>()

defineEmits<{
  retry: []
}>()

const hasPoints = computed(() => props.points.length > 0)

const onlinePoints = computed(() =>
  props.points.filter((p) => p.is_online && (p.cpu_pct != null || p.mem_pct != null)),
)

const sparklineLabels = computed(() =>
  onlinePoints.value.map((p) => formatPointTimeBeijing(p.recorded_at)),
)

const cpuSeries = computed(() =>
  onlinePoints.value.map((p) => p.cpu_pct ?? 0),
)

const memSeries = computed(() =>
  onlinePoints.value.map((p) => p.mem_pct ?? 0),
)

const latestCpu = computed(() => {
  const last = [...props.points].reverse().find((p) => p.is_online && p.cpu_pct != null)
  return last?.cpu_pct != null ? `${last.cpu_pct}%` : '—'
})

const latestMem = computed(() => {
  const last = [...props.points].reverse().find((p) => p.is_online && p.mem_pct != null)
  return last?.mem_pct != null ? `${last.mem_pct}%` : '—'
})

function formatSegment(seg: ServerMetricOfflineSegment): string {
  return `${formatPointTimeBeijing(seg.from)} – ${formatPointTimeBeijing(seg.to)}`
}
</script>
