const ROUTE_CHUNKS: Record<string, () => Promise<unknown>> = {
  '/': () => import('@/pages/DashboardPage.vue'),
  '/servers': () => import('@/pages/ServersPage.vue'),
  '/terminal': () => import('@/pages/TerminalPage.vue'),
  '/files': () => import('@/pages/FilesPage.vue'),
  '/push': () => import('@/pages/PushPage.vue'),
  '/scripts': () => import('@/pages/ScriptsPage.vue'),
  '/script-runs': () => import('@/pages/ScriptRunsPage.vue'),
  '/executions': () => import('@/pages/ScriptRunsPage.vue'),
  '/schedules': () => import('@/pages/SchedulesPage.vue'),
  '/retries': () => import('@/pages/RetriesPage.vue'),
  '/commands': () => import('@/pages/CommandsPage.vue'),
  '/alerts': () => import('@/pages/AlertsPage.vue'),
  '/audit': () => import('@/pages/AuditPage.vue'),
  '/settings': () => import('@/pages/SettingsPage.vue'),
}

const prefetched = new Set<string>()
const timers = new Map<string, ReturnType<typeof setTimeout>>()

export function scheduleRoutePrefetch(path: string, delayMs = 200) {
  const loader = ROUTE_CHUNKS[path]
  if (!loader || prefetched.has(path)) return

  const existing = timers.get(path)
  if (existing) clearTimeout(existing)

  timers.set(
    path,
    setTimeout(() => {
      timers.delete(path)
      if (prefetched.has(path)) return
      prefetched.add(path)
      void loader().catch(() => {
        prefetched.delete(path)
      })
    }, delayMs),
  )
}

export function cancelRoutePrefetch(path: string) {
  const t = timers.get(path)
  if (t) {
    clearTimeout(t)
    timers.delete(path)
  }
}
