<template>
  <div class="cpTripDetails">
    <cp-trip-leg-route-segment
      v-for="(segment, segmentIndex) in flightSegments"
      :key="`segment_${segmentIndex}`"
      :config="config"
      :locale="locale"
      :previous-segment-arrival="getPreviousSegmentArrival(segmentIndex)"
      :segment="segment"
      :segment-count="segmentCount"
      :segment-index="segmentIndex"
      :stop-duration="getStopDuration(segmentIndex)"
    />
  </div>
</template>

<script setup lang="ts">
import { DateTime } from 'luxon'
import { computed } from 'vue'

import type { CpTripDetailsConfig } from '@/constants/tripDetails/CpTripDetailsConfig'
import type { Flight } from '@/constants/tripDetails/Flight'

import { DEFAULT_CP_TRIP_DETAILS_CONFIG } from '@/constants/tripDetails/CpTripDetailsConfig'
import { getDuration } from '@/helpers/tripDetails'
import CpTripLegRouteSegment from './CpTripLegRouteSegment.vue'

interface Props {
  config?: CpTripDetailsConfig
  flight: Flight
  locale?: string
}

const props = withDefaults(defineProps<Props>(), {
  config: () => DEFAULT_CP_TRIP_DETAILS_CONFIG,
  locale: 'en',
})

const flightSegments = computed(() => props.flight.segments)
const segmentCount = computed(() => flightSegments.value.length)

const getSegmentTime = (segmentIndex: number, timeKey: 'arrival_date' | 'departure_date') => {
  return DateTime.fromISO(flightSegments.value[segmentIndex]?.[timeKey])
}

const getPreviousSegmentArrival = (segmentIndex: number) => {
  return getSegmentTime(segmentIndex - 1, 'arrival_date')
}

const getStopDuration = (segmentIndex: number) => {
  if (segmentCount.value < 2) return null

  const departure = getSegmentTime(segmentIndex, 'departure_date')
  const arrival = getPreviousSegmentArrival(segmentIndex)

  return getDuration(departure, arrival)
}
</script>

<style lang="scss">
.cpTripDetails {
  padding: var(--cp-spacing-xl) var(--cp-spacing-md);
}
</style>
