<script setup lang="ts">
import { onLoad, onReady } from '@dcloudio/uni-app'
import { computed, ref, type Component } from 'vue'
import { useI18n } from 'vue-i18n'
import TopicMemberZone from './components/topic-member-zone.vue'
import TopicLiveSeafoodAir from './components/topic-live-seafood-air.vue'
import TopicMustEatList from './components/topic-must-eat-list.vue'
import TopicNewCalendar from './components/topic-new-calendar.vue'
import TopicFreshSeafoodToday from './components/topic-fresh-seafood-today.vue'
import type { RouteQueryMap } from './utils/featured-dish-query'

const { t } = useI18n()

const topic = ref('')
const routeQuery = ref<RouteQueryMap>({})

const VALID_TOPICS = [
  'member-zone',
  'live-seafood-air',
  'must-eat-list',
  'new-calendar',
  'fresh-seafood-today',
] as const

type QuickTopic = (typeof VALID_TOPICS)[number]

const topicComponentMap: Record<QuickTopic, Component> = {
  'member-zone': TopicMemberZone,
  'live-seafood-air': TopicLiveSeafoodAir,
  'must-eat-list': TopicMustEatList,
  'new-calendar': TopicNewCalendar,
  'fresh-seafood-today': TopicFreshSeafoodToday,
}

const topicTitleKeyMap: Record<QuickTopic, string> = {
  'member-zone': 'pages.home.quickTabs.memberZone',
  'live-seafood-air': 'pages.home.quickTabs.liveSeafoodAir',
  'must-eat-list': 'pages.home.quickTabs.mustEatList',
  'new-calendar': 'pages.home.quickTabs.newCalendar',
  'fresh-seafood-today': 'pages.home.quickTabs.freshSeafoodToday',
}

const categoryNameFromRoute = computed(() => {
  const name = routeQuery.value.categoryName
  return name ? decodeURIComponent(name) : ''
})

const pageTitle = computed(() => {
  if (categoryNameFromRoute.value) return categoryNameFromRoute.value
  const key = topicTitleKeyMap[topic.value as QuickTopic]
  return key ? t(key) : ''
})

const isValidTopic = computed(() =>
  VALID_TOPICS.includes(topic.value as QuickTopic),
)

const activeTopicComponent = computed(() => {
  if (!isValidTopic.value) return null
  return topicComponentMap[topic.value as QuickTopic] ?? null
})

onLoad((query?: Record<string, string | undefined>) => {
  topic.value = String(query?.topic ?? '')
  const { topic: _t, ...rest } = query ?? {}
  routeQuery.value = rest
})

onReady(() => {
  if (!isValidTopic.value) {
    uni.showToast({ title: '参数无效', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})
</script>

<template>
  <view class="quick-topic-root">
    <component
      v-if="activeTopicComponent"
      :is="activeTopicComponent"
      :page-title="pageTitle"
      :route-query="routeQuery"
    />
  </view>
</template>

<style scoped lang="scss">
.quick-topic-root {
  min-height: 100vh;
  height: 100vh;
}
</style>
