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

defineProps<{ trip: Trip }>()
defineEmits<{ select: [trip: Trip] }>()

function formatTime(dateStr: string) {
  return new Date(dateStr).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })
}

function legSummary(leg: Trip['legs'][0]) {
  const segs = leg.segments
  if (!segs.length) return ''
  const dep = segs[0]
  const arr = segs[segs.length - 1]
  const stops = segs.length - 1
  const stopsText = stops === 0 ? 'Directo' : `${stops} escala${stops > 1 ? 's' : ''}`
  return `${dep.departureCode} ${formatTime(dep.departureDate)} → ${arr.arrivalCode} ${formatTime(arr.arrivalDate)} · ${stopsText}`
}
</script>

<template>
  <div
    class="flex items-center justify-between px-3 py-2 rounded-lg border border-neutral-200 dark:border-neutral-700 hover:border-primary-400 cursor-pointer transition-colors"
    @click="$emit('select', trip)"
  >
    <div class="flex-1 min-w-0">
      <p v-for="(leg, i) in trip.legs" :key="i" class="text-sm truncate">
        <span class="text-xs font-medium text-muted mr-1">{{ i === 0 ? 'Ida' : 'Vta' }}</span>
        {{ legSummary(leg) }}
      </p>
    </div>
    <div class="shrink-0 ml-3 text-right">
      <span class="text-lg font-bold text-primary-600 dark:text-primary-400">
        {{ trip.totalCost.toFixed(0) }}<span class="text-xs">&euro;</span>
      </span>
    </div>
  </div>
</template>
