import type { Router } from 'vue-router';

const prefetchedPaths = new Set<string>();

/** 预取目标路径上所有 lazy route 的 JS chunk（侧边栏 hover/focus 时调用）。 */
export function prefetchRouteChunks(router: Router, path: string) {
  const key = path.split('?')[0] || '/';
  if (prefetchedPaths.has(key)) return;

  let matched = false;
  try {
    const resolved = router.resolve(path);
    for (const record of resolved.matched) {
      const loader = record.components?.default;
      if (typeof loader === 'function') {
        matched = true;
        void (loader as () => Promise<unknown>)();
      }
    }
  } catch {
    return;
  }

  if (matched) prefetchedPaths.add(key);
}
