<script setup lang="ts">
import type { Trip } from '~/server/utils/flightics'

defineProps<{ trip: Trip }>()

function formatFullDate(d: string) {
  return new Date(d).toLocaleDateString('es-ES', { weekday: 'short', day: 'numeric', month: 'long' })
}

function legDuration(leg: Trip['legs'][0]) {
  const segs = leg.segments
  if (!segs.length) return ''
  const depMs = segs[0].departureTimestamp * 1000
  const arrMs = segs[segs.length - 1].arrivalTimestamp * 1000
  const diffMin = Math.round((arrMs - depMs) / 60000)
  const h = Math.floor(diffMin / 60)
  const m = diffMin % 60
  return `${h}h ${m}m`
}
</script>

<template>
  <div class="space-y-4">
    <UCard v-for="(leg, i) in trip.legs" :key="i">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <UBadge :label="i === 0 ? 'Ida' : 'Vuelta'" :color="i === 0 ? 'primary' : 'info'" variant="subtle" />
            <span class="text-sm text-neutral-500">{{ formatFullDate(leg.segments[0].departureDate) }}</span>
          </div>
          <div class="flex items-center gap-2 text-sm text-muted">
            <UIcon name="i-lucide-timer" class="text-xs" />
            {{ legDuration(leg) }}
            <template v-if="leg.segments.length > 1">
              · {{ leg.segments.length - 1 }} escala{{ leg.segments.length > 2 ? 's' : '' }}
            </template>
          </div>
        </div>
      </template>

      <DetailSegmentCard
        v-for="(seg, j) in leg.segments"
        :key="j"
        :segment="seg"
        :show-divider="j > 0"
      />
    </UCard>
  </div>
</template>
