// Tiny history-API router for the operator app — no library, no bundler.
// Routes: / (overview) · /demo (demo line) · /projects/:slug (board) · /projects/:slug/plan · /projects/:slug/reviews
const { useState: useStateRouter, useEffect: useEffectRouter } = React;

function matchRoute(pathname) {
  if (pathname === "/" || pathname === "") return { name: "overview", slug: null };
  if (pathname === "/demo" || pathname === "/demo/") return { name: "demo", slug: null }; // demo line view — never "unknown" (redline 1)
  const m = pathname.match(/^\/projects\/([^/]+)(?:\/(plan|reviews))?\/?$/);
  if (m) return { name: m[2] || "board", slug: decodeURIComponent(m[1]) };
  return { name: "unknown", slug: null };
}

function navigate(path) {
  if (path === window.location.pathname) return;
  window.history.pushState({}, "", path);
  window.dispatchEvent(new Event("al-navigate"));
}

function useRoute() {
  const [path, setPath] = useStateRouter(() => window.location.pathname);
  useEffectRouter(() => {
    const onChange = () => setPath(window.location.pathname);
    window.addEventListener("popstate", onChange);   // back/forward buttons
    window.addEventListener("al-navigate", onChange); // in-app navigate()
    return () => { window.removeEventListener("popstate", onChange); window.removeEventListener("al-navigate", onChange); };
  }, []);
  return { path, ...matchRoute(path) };
}

window.matchRoute = matchRoute;
window.navigate = navigate;
window.useRoute = useRoute;
