<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { appMerchantFeaturedListPost, appRecipeCategoryListGet } from '@/service'
import { getFeaturedDishList } from '@/pages-store/service'
import { useUserStore, useConfigStore } from '@/store'
import SearchDishResultItem from '@/pages/search/components/search-dish-result-item.vue'
import { buildMustEatListQuery, type RouteQueryMap } from '../utils/featured-dish-query'
import { parseFeaturedDishListRes } from '@/utils/featuredDish'

type MustEatTab = 'merchant' | 'dish'
type RecipeCategoryItem = { id?: string | number; categoryName?: string }

const props = defineProps<{
  routeQuery?: RouteQueryMap
  pageTitle?: string
}>()

const { t } = useI18n()
const userStore = useUserStore()
const configStore = useConfigStore()

const activeTab = ref<MustEatTab>('merchant')
const tabIndex = ref(0)

const tabs = computed(() => [
  { label: t('pages.home.mustEatListTabs.merchant'), value: 'merchant' as MustEatTab },
  { label: t('pages.home.mustEatListTabs.dish'), value: 'dish' as MustEatTab },
])

const paging = ref<ZPagingInstance | null>(null)
const dataList = ref<Record<string, unknown>[]>([])
const merchantSourceList = ref<Record<string, unknown>[]>([])
const recipeCategoryList = ref<RecipeCategoryItem[]>([])
const activeCategoryId = ref<string | number>('')

const categoryTabs = computed(() => [
  { id: '' as const, name: t('pages.home.mustEatListTabs.all') },
  ...recipeCategoryList.value.map((c) => ({
    id: c.id ?? '',
    name: String(c.categoryName ?? ''),
  })),
])

const activeCategoryIndex = computed(() => {
  const idx = categoryTabs.value.findIndex(
    (c) => String(c.id) === String(activeCategoryId.value),
  )
  return idx >= 0 ? idx : 0
})

onMounted(() => {
  appRecipeCategoryListGet({}).then((res) => {
    recipeCategoryList.value = (res.data as RecipeCategoryItem[]) || []
  })
})

function onTabChange(index: number) {
  tabIndex.value = index
  activeTab.value = tabs.value[index]?.value ?? 'merchant'
  dataList.value = []
  paging.value?.reload()
}

function onCategoryChange(id: string | number) {
  if (String(activeCategoryId.value) === String(id)) return
  activeCategoryId.value = id
  dataList.value = []
  paging.value?.reload()
}

function categoryNameById(id: string | number): string {
  if (id === '' || id == null) return ''
  const hit = recipeCategoryList.value.find((c) => String(c.id) === String(id))
  return String(hit?.categoryName ?? '')
}

function filterMerchantsByCategory(list: Record<string, unknown>[]) {
  const name = categoryNameById(activeCategoryId.value)
  if (!name) return list
  return list.filter((item) => {
    const zh = item.merchantCategoryNamesZh as string[] | undefined
    const en = item.merchantCategoryNamesEn as string[] | undefined
    const names = [...(zh || []), ...(en || [])]
    return names.some((n) => n.includes(name) || name.includes(n))
  })
}

async function onQuery(pageNum: number, pageSize: number) {
  try {
    if (activeTab.value === 'merchant') {
      if (pageNum > 1) {
        await paging.value?.completeByNoMore([], true)
        return
      }
      const res = await appMerchantFeaturedListPost({
        body: {
          lat: userStore.userLocation.latitude,
          lng: userStore.userLocation.longitude,
        },
      })
      const list = Array.isArray((res as { data?: unknown[] })?.data)
        ? ((res as { data: unknown[] }).data as Record<string, unknown>[])
        : []
      merchantSourceList.value = list
      const filtered = filterMerchantsByCategory(list)
      await paging.value?.completeByTotal(filtered, filtered.length)
      return
    }

    const filterBody = buildMustEatListQuery(props.routeQuery)
    if (activeCategoryId.value !== '' && activeCategoryId.value != null) {
      filterBody.recipeCategoryId = activeCategoryId.value
    }
    const res = await getFeaturedDishList({
      pageNum,
      pageSize,
      ...filterBody,
    })
    const { rows, total } = parseFeaturedDishListRes(res)
    await paging.value?.completeByTotal(rows, total)
  } catch {
    await paging.value?.complete(false)
  }
}

function merchantImagePair(item: Record<string, unknown>): [string, string] {
  const shop = String(item.shopImages ?? '')
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)
  const logo = String(item.logo ?? '').trim()
  let a = shop[0] || logo || ''
  let b = shop[1] || shop[0] || logo || ''
  if (!a && !b) return ['', '']
  if (!b) b = a
  if (!a) a = b
  return [a, b]
}

function merchantCategoryLine(item: Record<string, unknown>): string {
  const zh = item.merchantCategoryNamesZh as string[] | undefined
  const en = item.merchantCategoryNamesEn as string[] | undefined
  if (uni.getLocale() === 'zh-Hans' && zh?.length) return zh[0] || ''
  if (en?.length) return en[0] || ''
  if (zh?.length) return zh[0] || ''
  return ''
}

function ratingStars(rating?: unknown) {
  return Math.min(5, Math.max(0, Math.round(Number(rating) || 0)))
}

function ratingText(rating?: unknown) {
  const n = Number(rating)
  return Number.isFinite(n) ? n.toFixed(1) : '0.0'
}

function openMerchant(item: Record<string, unknown>) {
  if (item?.id == null) return
  uni.navigateTo({
    url: `/pages-store/pages/store/index?id=${item.id}`,
  })
}
</script>

<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    bg-color="#f2f2f2"
    :auto="true"
    @query="onQuery"
  >
    <template #top>
      <navbar :title="pageTitle || ''" />
      <view class="must-eat-tabbar">
        <view class="must-eat-segment">
          <view
            class="must-eat-segment__thumb"
            :style="{ transform: `translateX(${tabIndex * 100}%)` }"
          />
          <view
            v-for="(tab, index) in tabs"
            :key="tab.value"
            class="must-eat-segment__item"
            :class="{ 'must-eat-segment__item--on': tabIndex === index }"
            @click="onTabChange(index)"
          >
            <text class="must-eat-segment__text">{{ tab.label }}</text>
          </view>
        </view>

        <scroll-view
          class="must-eat-categories"
          scroll-x
          :show-scrollbar="false"
          enable-flex
        >
          <view class="must-eat-categories__track">
            <view
              v-for="(cat, index) in categoryTabs"
              :key="String(cat.id === '' ? 'all' : cat.id)"
              class="must-eat-categories__item"
              :class="{
                'must-eat-categories__item--on': activeCategoryIndex === index,
              }"
              @click="onCategoryChange(cat.id)"
            >
              <text class="must-eat-categories__text">{{ cat.name }}</text>
              <view
                v-if="activeCategoryIndex === index"
                class="must-eat-categories__line"
              />
            </view>
            <view class="must-eat-categories__tail" />
          </view>
        </scroll-view>
      </view>
    </template>

    <!-- 商家：精选商家，一行一条（同 home-store 卡片） -->
    <view v-if="activeTab === 'merchant'" class="must-eat-list px-24rpx pb-40rpx pt-8rpx">
      <view
        v-for="(item, index) in dataList"
        :key="String(item.id ?? index)"
        class="merchant-card"
        @click="openMerchant(item)"
      >
        <view class="merchant-card__imgs">
          <view
            v-for="(src, ii) in merchantImagePair(item)"
            :key="ii"
            class="merchant-card__img-slot"
            :class="
              ii === 0
                ? 'merchant-card__img-slot--first'
                : 'merchant-card__img-slot--last'
            "
          >
            <image
              v-if="src"
              class="merchant-card__img"
              :src="src"
              mode="aspectFill"
            />
            <view v-else class="merchant-card__img merchant-card__img--empty" />
          </view>
        </view>
        <view class="merchant-card__body">
          <text class="merchant-card__name">{{ item.merchantName }}</text>
          <text
            v-if="merchantCategoryLine(item)"
            class="merchant-card__cate"
          >{{ merchantCategoryLine(item) }}</text>
          <view class="merchant-card__rating">
            <text
              v-for="si in [1, 2, 3, 4, 5]"
              :key="si"
              class="merchant-card__star"
              :class="{
                'merchant-card__star--on': si <= ratingStars(item.rating),
              }"
            >★</text>
            <text class="merchant-card__score">{{ ratingText(item.rating) }}</text>
          </view>
          <text class="merchant-card__tag">{{ t('pages.home.brandTag') }}</text>
        </view>
        <view class="merchant-card__go" @click.stop="openMerchant(item)">
          <view class="i-carbon:chevron-right merchant-card__go-icon"></view>
        </view>
      </view>
    </view>

    <!-- 商品：销量排序，一行一条 -->
    <view v-else class="must-eat-dish-list pb-40rpx pt-8rpx">
      <search-dish-result-item
        v-for="item in dataList"
        :key="String(item.id ?? item.merchantId)"
        :item="item as any"
      />
    </view>

    <template #bottom>
      <view class="h-24rpx"></view>
      <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
    </template>
  </z-paging>
</template>

<style scoped lang="scss">
.must-eat-tabbar {
  background: #fff;
  padding: 16rpx 24rpx 0;
}

.must-eat-segment {
  position: relative;
  display: flex;
  align-items: stretch;
  height: 80rpx;
  padding: 8rpx;
  background: #ececec;
  border-radius: 999rpx;
  box-sizing: border-box;
  overflow: hidden;
}

.must-eat-segment__thumb {
  position: absolute;
  left: 8rpx;
  top: 8rpx;
  width: calc((100% - 16rpx) / 2);
  height: calc(100% - 16rpx);
  background: #fff;
  border-radius: 999rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 0;
}

.must-eat-segment__item {
  position: relative;
  z-index: 1;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.must-eat-segment__text {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
  line-height: 1.2;
  transition: color 0.2s, font-weight 0.2s;
}

.must-eat-segment__item--on .must-eat-segment__text {
  color: #14181b;
  font-weight: 600;
}

.must-eat-categories {
  width: 100%;
  margin-top: 8rpx;
  white-space: nowrap;
}

.must-eat-categories__track {
  display: inline-flex;
  align-items: flex-end;
  min-width: 100%;
  padding: 8rpx 0 4rpx;
}

.must-eat-categories__item {
  position: relative;
  flex-shrink: 0;
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 16rpx 28rpx 14rpx;
}

.must-eat-categories__item--on {
  padding-bottom: 10rpx;
}

.must-eat-categories__text {
  font-size: 28rpx;
  color: #999;
  font-weight: 400;
  line-height: 1.3;
  white-space: nowrap;
}

.must-eat-categories__item--on .must-eat-categories__text {
  color: #14181b;
  font-weight: 700;
}

.must-eat-categories__line {
  margin-top: 10rpx;
  width: 40rpx;
  height: 6rpx;
  background: #14181b;
  border-radius: 6rpx;
}

.must-eat-categories__tail {
  flex-shrink: 0;
  width: 24rpx;
  height: 1rpx;
}

.merchant-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  background: #fff;
  border-radius: 24rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);
}

.merchant-card__imgs {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  width: 152rpx;
  flex-shrink: 0;
}

.merchant-card__img-slot {
  width: 152rpx;
  height: 96rpx;
  overflow: hidden;
  background: #e8eaed;
}

.merchant-card__img-slot--first {
  border-radius: 12rpx 12rpx 0 0;
}

.merchant-card__img-slot--last {
  border-radius: 0 0 12rpx 12rpx;
}

.merchant-card__img {
  width: 100%;
  height: 100%;
  display: block;
}

.merchant-card__body {
  flex: 1;
  min-width: 0;
  padding: 0 20rpx 0 8rpx;
}

.merchant-card__name {
  font-size: 30rpx;
  font-weight: 600;
  color: #14181b;
  line-height: 1.35;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.merchant-card__cate {
  margin-top: 8rpx;
  font-size: 26rpx;
  color: #333;
  display: block;
}

.merchant-card__rating {
  margin-top: 12rpx;
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.merchant-card__star {
  font-size: 22rpx;
  color: #e0e0e0;
}

.merchant-card__star--on {
  color: #ffb400;
}

.merchant-card__score {
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #666;
}

.merchant-card__tag {
  margin-top: 10rpx;
  font-size: 22rpx;
  color: #ce7138;
}

.merchant-card__go {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.merchant-card__go-icon {
  font-size: 36rpx;
  color: #999;
}

.must-eat-dish-list {
  background: #fff;
}
</style>
