<script setup lang="ts">
import { onMounted } from 'vue'
import { appDiningProfileGet } from '@/service'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

function hasProfileData(data: unknown) {
  if (!data) return false
  if (typeof data === 'object') {
    const map = data as Record<string, unknown>
    return Object.keys(map).some((k) => {
      const v = map[k]
      if (Array.isArray(v)) return v.length > 0
      return v != null && String(v).trim() !== ''
    })
  }
  return false
}
function goPreference() {
  const current = getCurrentPages?.().slice(-1)[0]
  if (current?.route === 'pages/ai/diet-preference/index') return
  uni.navigateTo({
    url: '/pages/ai/diet-preference/index',
  })
}

async function redirectToTarget() {
  let done = false
  try {
    const res = await appDiningProfileGet({})
    done = hasProfileData(res?.data)
  } catch (e) {
    // 查询失败时兜底读本地标记，避免阻塞入口
    done = !!uni.getStorageSync('ai_diet_pref_done')
  }
  uni.redirectTo({
    url: done ? '/pages/ai/chat/index' : '/pages/ai/diet-preference/index',
  })
}

onMounted(() => {
  redirectToTarget()
})
</script>

<template>
  <view>
    <navbar :title="t('navbar-ai-recommend')">
      <template #right>
        <view class="nav-action" @click="goPreference">
          {{ t('common.go-to-settings') }}
        </view>
      </template>
    </navbar>
    <view class="ai-recommend-loading">
      <text>{{ t('pages.ai.recommend.loading') }}</text>
    </view>
  </view>
</template>

<style scoped lang="scss">
.ai-recommend-loading {
  min-height: 60vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333;
}

.nav-action {
  font-size: 24rpx;
  color: #14181b;
  padding: 8rpx 0 8rpx 16rpx;
}
</style>

