const routePrefetchLoaders = {
  "/dashboard": () => import("@/pages/Dashboard"),
  "/dashboard/profile": () => import("@/pages/Profile"),
  "/dashboard/documents": () => import("@/pages/Documents"),
  "/dashboard/requests": () => import("@/pages/Requests"),
  "/dashboard/requests/:id": () => import("@/pages/RequestDetail"),
  "/dashboard/requests/:id/edit": () => import("@/pages/EditRequest"),
  "/dashboard/requests/new": () => import("@/pages/NewRequest"),
  "/dashboard/reservation-salle": () => import("@/pages/ReservationSalle"),
  "/dashboard/materiel-evenementiel": () => import("@/pages/DemandeMaterielEvenementiel"),
  "/dashboard/associations": () => import("@/pages/AssociationDirectoryPortal"),
  "/admin": () => import("@/pages/Admin"),
  "/admin/stats-report": () => import("@/pages/StatsReportArchiveView"),
  "/associations": () => import("@/pages/AssociationDirectoryPortal"),
  "/associations/:id": () => import("@/pages/AssociationPublicProfile"),
  "/associations/carte": () => import("@/pages/AssociationMapPublic"),
  "/faq": () => import("@/pages/FAQ"),
  "/confidentialite": () => import("@/pages/PrivacyPolicy"),
  "/mentions-legales": () => import("@/pages/LegalNotice"),
  "/cookies": () => import("@/pages/CookiesPolicy"),
  "/cgu": () => import("@/pages/TermsOfService"),
} as const;

const prefetchedRoutes = new Set<string>();

function normalizePrefetchRoute(path: string) {
  if (!path) return "";
  if (path === "/admin" || path.startsWith("/admin?")) return "/admin";
  if (path === "/admin/stats-report" || path.startsWith("/admin/stats-report?")) return "/admin/stats-report";
  if (path === "/confidentialite" || path.startsWith("/confidentialite?")) return "/confidentialite";
  if (path === "/mentions-legales" || path.startsWith("/mentions-legales?")) return "/mentions-legales";
  if (path === "/cookies" || path.startsWith("/cookies?")) return "/cookies";
  if (path === "/cgu" || path.startsWith("/cgu?")) return "/cgu";
  if (/^\/dashboard\/requests\/\d+\/edit$/.test(path)) return "/dashboard/requests/:id/edit";
  if (/^\/dashboard\/requests\/\d+$/.test(path)) return "/dashboard/requests/:id";
  if (/^\/dashboard\/requests\/[^/]+/.test(path) && !path.endsWith("/edit")) return "/dashboard/requests";
  if (/^\/associations\/\d+$/.test(path)) return "/associations/:id";
  return path;
}

export function prefetchRoute(path: string) {
  const normalizedPath = normalizePrefetchRoute(path);
  const loader = routePrefetchLoaders[normalizedPath as keyof typeof routePrefetchLoaders];
  if (!loader || prefetchedRoutes.has(normalizedPath)) {
    return;
  }

  prefetchedRoutes.add(normalizedPath);
  void loader().catch(() => {
    prefetchedRoutes.delete(normalizedPath);
  });
}

export function buildRoutePrefetchHandlers(path: string) {
  const trigger = () => prefetchRoute(path);

  return {
    onMouseEnter: trigger,
    onFocus: trigger,
    onTouchStart: trigger,
  };
}
