// Rôle : synchronise la navigation hash avec l'état React.
import { useEffect, useState } from "react";

function currentRoute() {
  const hashRoute = location.hash.replace(/^#/, "");
  if (hashRoute) return hashRoute.replace(/#.+$/, "");
  const path = location.pathname.replace(/\/+$/, "") || "/";
  if (path === "/mhwilds") return "/games/mhwilds";
  if (path === "/mhwilds/monsters") return "/games/mhwilds/monsters";
  if (path === "/mhwilds/endemic") return "/games/mhwilds/endemic";
  if (path === "/mhwilds/lists") return "/games/mhwilds/lists";
  return path;
}

export function navigate(path) {
  location.hash = path;
}

export function useHashRoute() {
  const [route, setRoute] = useState(currentRoute);
  useEffect(() => {
    const onHashChange = () => setRoute(currentRoute());
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, []);
  return route;
}
