<script setup>
import { computed } from 'vue'
import Card from '@/components/ui/Card.vue'
import { observationCodeLabel } from '@/api/normalize'

const props = defineProps({
  observations: { type: Array, default: () => [] },
})

const latestByCode = computed(() => {
  const map = new Map()
  for (const obs of props.observations) {
    const existing = map.get(obs.observationCode)
    if (!existing || new Date(obs.recordedAt) > new Date(existing.recordedAt)) {
      map.set(obs.observationCode, obs)
    }
  }
  return [...map.values()].sort((a, b) =>
    observationCodeLabel(a.observationCode).localeCompare(observationCodeLabel(b.observationCode)),
  )
})
</script>

<template>
  <Card>
    <template #header>
      <h2 class="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
        Latest Vitals
      </h2>
    </template>

    <div v-if="latestByCode.length" class="grid grid-cols-2 gap-4 sm:grid-cols-3">
      <div
        v-for="obs in latestByCode"
        :key="obs.id ?? obs.observationCode"
        class="rounded-lg bg-gray-50 p-4 dark:bg-gray-800"
      >
        <div class="text-xs text-gray-500 dark:text-gray-400">
          {{ observationCodeLabel(obs.observationCode) }}
        </div>
        <div class="text-lg font-semibold text-gray-900 dark:text-white">
          {{ obs.value }}
          <span class="text-sm font-normal text-gray-500 dark:text-gray-400">{{ obs.unit }}</span>
        </div>
      </div>
    </div>
    <p v-else class="text-sm text-gray-500 dark:text-gray-400">No observations recorded</p>
  </Card>
</template>
