<template>
  <FlexRow align="center" :margin="[0,0,10,100]" :gap="12">
    <template v-if="canShow">
      <template v-if="userPreferredWay">
        <Tag :text="getRouteToNextBestWayText(finalWay)" touchable @click="emit('focusRoute')" />
        <Text :text="formatDistance(toNextRoute[finalWay]?.distance)" />
        <Text :text="formatDuration(toNextRoute[finalWay]?.duration)" />
      </template>
      <template v-else>
        <Tag :text="'推荐 ' + getRouteToNextBestWayText(finalWay)" touchable @click="emit('focusRoute')" />
        <Text :text="formatDistance(toNextRoute[finalWay]?.distance)" />
        <Text :text="formatDuration(toNextRoute[finalWay]?.duration)" />
      </template>
    </template>
  </FlexRow>
  <slot name="extra" :finalWay="finalWay" />
</template>

<script setup lang="ts">
import { formatDistance, formatDuration, getRouteToNextBestWayText, type RouteInfo, type RouteToNextBestWay } from '@/api/traval/RouteApi';
import Text from '@/components/basic/Text.vue';
import Tag from '@/components/display/Tag.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import { computed } from 'vue';

const props = defineProps<{
  toNextRoute: RouteInfo['items'][number]['toNextRoute'],
  toNextBestWay?: RouteToNextBestWay|'',
  userPreferredWay?: RouteToNextBestWay|'',
}>();

const emit = defineEmits([ 'focusRoute' ]);

const canShow = computed(() => props.toNextRoute && Object.keys(props.toNextRoute).length > 0);
const finalWay = computed(() => {
  let way = props.userPreferredWay || props.toNextBestWay || 'transit';
  if (!props.toNextRoute[way] 
    || !props.toNextRoute[way].steps?.length 
    || (props.toNextRoute[way].steps.length ) < 2
  ) {
    const keys = Object.keys(props.toNextRoute);
    for (const key of keys) {
      if ((props.toNextRoute[key as RouteToNextBestWay].steps?.length || 0) > 1) {
        way = key as RouteToNextBestWay;
        break;
      }
    }
  }
  return way;
});
</script>