'use client'

import { useEffect, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useCurrentUser } from '@/hooks/auth'
import { useToken } from '@/hooks/auth'

const PUBLIC_PREFETCH_TARGETS = ['/']

const AUTH_PREFETCH_TARGETS = [
  '/contact',
  '/profile',
  '/profile/edit',
  '/profile/account',
  '/vip',
  '/wallet',
  '/wallet/charge',
  '/wallet/charge/result',
  '/wallet/transactions',
  '/leaderboard',
  '/crushcoin',
  '/generate/image',
  '/generate/image-2-image',
  '/generate/image-edit',
  '/generate/image-2-background',
  '/explore',
  '/creator',
  '/create/type',
  '/create/dialogue',
  '/create/character',
  '/create/image',
]

// 受保护路由前缀列表（需要登录才能访问的路由）
const PROTECTED_ROUTE_PREFIXES = [
  '/profile',
  '/create',
  '/settings',
  '/login/fields',
  '/chat',
  '/contact',
  '/vip',
  '/wallet',
  '/crushcoin',
  '/leaderboard',
  '/generate',
  '/explore',
  '/creator',
]

// 检查路由是否是受保护路由
const isProtectedRoute = (href: string): boolean => {
  return PROTECTED_ROUTE_PREFIXES.some((prefix) => href.startsWith(prefix))
}

const DEFAULT_PREFETCH_TARGETS = [...PUBLIC_PREFETCH_TARGETS, ...AUTH_PREFETCH_TARGETS]

type NullableRoute = string | null | undefined

const prefetchedRouteCache = new Set<string>()

export function usePrefetchRoutes(
  routes?: NullableRoute[],
  options?: {
    limit?: number
  }
) {
  const router = useRouter()
  const { isLogin } = useToken()
  const normalizedRoutes = useMemo(() => {
    if (!routes || routes.length === 0) return []
    return routes.filter(Boolean) as string[]
  }, [routes])
  const limit = options?.limit ?? Infinity

  useEffect(() => {
    if (!normalizedRoutes.length) return
    let count = 0
    for (const href of normalizedRoutes) {
      if (!href || prefetchedRouteCache.has(href)) continue
      // 如果未登录且是受保护路由，跳过 prefetch，避免缓存重定向响应
      if (!isLogin && isProtectedRoute(href)) continue
      prefetchedRouteCache.add(href)
      router.prefetch(href)
      count += 1
      if (count >= limit) break
    }
  }, [limit, normalizedRoutes, router, isLogin])
}

export function useGlobalPrefetchRoutes(extraRoutes?: NullableRoute[]) {
  const { data: user } = useCurrentUser()
  const isAuthenticated = !!user

  const protectedTargets = useMemo(() => {
    const routes = new Set(AUTH_PREFETCH_TARGETS)
    extraRoutes?.forEach((href) => {
      if (href && href !== '/') {
        routes.add(href)
      }
    })
    return Array.from(routes)
  }, [extraRoutes])

  usePrefetchRoutes(PUBLIC_PREFETCH_TARGETS)
  usePrefetchRoutes(isAuthenticated ? protectedTargets : [])
}

export const GLOBAL_PREFETCH_ROUTES = DEFAULT_PREFETCH_TARGETS
