<template>
  <div class="space-y-3">
    <Heading v-if="title" :level="3" weight="semibold">{{ title }}</Heading>

    <div v-if="stages.length" class="divide-y divide-base-200">
      <div
        v-for="(stage, index) in stages"
        :key="stage.key || `${index}-${stage.from || ''}-${stage.to || ''}`"
        class="py-3 flex flex-wrap items-start justify-between gap-3"
      >
        <div class="min-w-0">
          <div class="text-sm font-medium text-base-content">
            <span v-if="stage.from || stage.to">
              {{ stage.from || stage.label || '—' }} → {{ stage.to || stage.label || '—' }}
            </span>
            <span v-else>
              {{ stage.label || '—' }}
            </span>
          </div>
          <div v-if="stage.meta?.length" class="text-xs text-base-content/60 mt-1 flex flex-wrap gap-x-3 gap-y-1">
            <span v-for="item in stage.meta" :key="item">{{ item }}</span>
          </div>
        </div>

        <div class="flex items-center gap-2 shrink-0">
          <span v-if="stage.transportType" class="badge badge-sm badge-outline">
            {{ stage.transportType === 'rail' ? '🚂 ЖД' : '🚛 Авто' }}
          </span>
          <span v-if="stage.distanceKm" class="text-sm text-base-content/70">
            {{ formatDistance(stage.distanceKm) }} км
          </span>
        </div>
      </div>
    </div>

    <Text v-else tone="muted">{{ emptyText }}</Text>
  </div>
</template>

<script setup lang="ts">
export type RouteStageItem = {
  key?: string
  from?: string | null
  to?: string | null
  label?: string | null
  distanceKm?: number | null
  durationSeconds?: number | null
  transportType?: string | null
  meta?: string[]
}

const props = withDefaults(defineProps<{ title?: string; stages?: RouteStageItem[]; emptyText?: string }>(), {
  stages: () => [],
  title: '',
  emptyText: 'Этапы не найдены.'
})

const stages = computed(() => (props.stages || []).filter(Boolean))

const formatDistance = (km: number | null | undefined) => {
  if (!km) return '0'
  return Math.round(km).toLocaleString()
}

</script>
