import { useLoginStore } from '~/stores/LoginStore'
import { useBaseStore } from '~/stores/BaseStore'
import { useUserDetailStore } from '~/stores/UserDetailStore'

export default defineNuxtRouteMiddleware((to, from) => {
  if (import.meta.client) {
    const loginStore = useLoginStore()
    const baseStore = useBaseStore()
    const isLogin = loginStore.isLogin
    const idType = baseStore.idType

    // 取得不帶語系前綴的路徑
    const pathWithoutLocale = to.path.replace(/^\/(?:en|zh-Hant)(?:\/|$)/, '/')
    const normalizedPath = pathWithoutLocale.startsWith('/')
      ? pathWithoutLocale
      : '/' + pathWithoutLocale

    // 0. 全域擷取並記憶推薦碼 (無論是否登入)
    if (normalizedPath === '/shared') {
      const userCode = to.query.userCode as string
      if (userCode) {
        baseStore.inviteCache = userCode
      }
    }

    // 1. 公開頁面白名單 (不需要登入即可訪問)
    const publicPages = ['/welcome', '/forgot-password', '/', '/member/home']
    const isAuthPage =
      (normalizedPath.startsWith('/login') && normalizedPath !== '/login/select') ||
      normalizedPath === '/welcome'
    const isPublicPage =
      publicPages.includes(normalizedPath) ||
      isAuthPage ||
      normalizedPath.startsWith('/register') ||
      (normalizedPath.startsWith('/member/detail/') && !normalizedPath.endsWith('/reserve'))

    if (!isLogin) {
      if (normalizedPath === '/shared') {
        return navigateTo('/login')
      }

      if (isPublicPage) {
        return
      }
      return navigateTo('/login')
    }

    if (isLogin) {
      const userDetailStore = useUserDetailStore()

      // 檢查是否欠缺 selectType，如果是，允許前往 /register/form 填寫
      if (!userDetailStore.userDetail?.selectType && normalizedPath === '/register/form') {
        return // 提早放行，不執行後續信箱與手機的強制導向
      } 
      // 如果 Email 未驗證，且不在 Email 驗證頁，則強制導向
      if (
        userDetailStore.isEmailVerify === '0' &&
        normalizedPath !== '/register/email-verification'
      ) {
        return navigateTo(
          `/register/email-verification?email=${encodeURIComponent(userDetailStore.email)}`,
        )
      }
      // 如果手機未驗證，且不在手機驗證頁 (且 Email 已驗證)，則強制導向
      if (
        userDetailStore.isEmailVerify === '1' &&
        userDetailStore.isPhoneVerify === '0' &&
        normalizedPath !== '/register/phone-verification'
      ) {
        return navigateTo('/register/phone-verification')
      }

      const idType = baseStore.idType
      const userDetail = userDetailStore.userDetail
      // ... 角色跳轉邏輯 ...
      if (isAuthPage && normalizedPath !== '/') {
        if (idType === 'member') {
          return navigateTo('/member/home')
        } else if (idType === 'partner') {
          return navigateTo('/partner/reserve')
        }
      }
    }

    const path = normalizedPath

    // 2. 共用功能頁面 (需要登入，但不限制角色：如聊天、卡片、收藏、通知)
    const sharedPaths = ['/chat', '/cards', '/favorite', '/notification']
    if (sharedPaths.some((p) => path.startsWith(p))) {
      return
    }

    // 3. 角色專屬頁面權限檢查
    // 如果 idType 為 null，說明身分還在從 storage 讀取中，先不執行重新導向
    if (idType === null) return

    // Member 權限檢查：禁止進入 /partner
    if (idType === 'member') {
      if (path.startsWith('/partner')) {
        return navigateTo('/member/home')
      }
    }

    // Partner 權限檢查：禁止進入 /member
    if (idType === 'partner') {
      if (path.startsWith('/member')) {
        return navigateTo('/partner/reserve')
      }
    }
  }
})
