import type { RouteRecordRaw } from 'vue-router'

/**
 * 路由预加载工具
 * 在空闲时预加载可能即将访问的路由组件,提升页面切换速度
 */

/** 预加载策略 */
export type PrefetchStrategy = 'hover' | 'visible' | 'idle'

/** 已预加载的路径集合 */
const prefetchedPaths = new Set<string>()

/**
 * 使用 requestIdleCallback 预加载路由组件
 * 在浏览器空闲时执行,不影响主要交互
 */
export function prefetchRoute(componentPath: string): void {
  if (prefetchedPaths.has(componentPath)) return

  // 规范化路径
  const normalized = componentPath.replace(/\\/g, '/')

  // 使用动态 import 预加载组件
  const loaders = import.meta.glob('@/views/**/*.vue')
  const loader = loaders[`/src/views/${normalized}.vue`] || loaders[`./src/views/${normalized}.vue`]

  if (loader) {
    prefetchedPaths.add(componentPath)
    // 使用 requestIdleCallback 在空闲时预加载
    if ('requestIdleCallback' in window) {
      ;(window as any).requestIdleCallback(() => loader())
    } else {
      // 降级:使用 setTimeout
      setTimeout(() => loader(), 200)
    }
  }
}

/**
 * 预加载一组路由
 */
export function prefetchRoutes(paths: string[]): void {
  paths.forEach(prefetchRoute)
}

/**
 * 判断路由是否已预加载
 */
export function isPrefetched(path: string): boolean {
  return prefetchedPaths.has(path)
}