// Minimal client-side router — no library, this app has no bundler/npm-in-
// browser. Six routes, matched against `location.pathname`. History state
// (via pushState's second arg) carries transient data — e.g. a freshly
// opened, not-yet-saved template's document — that isn't fetchable by URL
// alone. See pages/project.jsx.

const ROUTES = [
  { name: "home", pattern: /^\/$/ },
  { name: "brand", pattern: /^\/brand\/?$/ },
  { name: "templates", pattern: /^\/templates\/?$/ },
  { name: "generate", pattern: /^\/generate\/?$/ },
  { name: "profile", pattern: /^\/profile\/?$/ },
  { name: "project", pattern: /^\/project\/([^/]+)\/?$/, param: "id" },
];

function parseRoute(pathname) {
  for (const r of ROUTES) {
    const m = pathname.match(r.pattern);
    if (m) return { name: r.name, ...(r.param ? { [r.param]: decodeURIComponent(m[1]) } : {}) };
  }
  return { name: "home" };
}

function useRouter() {
  const [route, setRoute] = useState(() => ({ ...parseRoute(location.pathname), state: history.state || null }));

  useEffect(() => {
    const onPop = () => setRoute({ ...parseRoute(location.pathname), state: history.state || null });
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const navigate = (path, state, { replace = false } = {}) => {
    if (replace) history.replaceState(state || null, "", path);
    else history.pushState(state || null, "", path);
    setRoute({ ...parseRoute(path), state: state || null });
  };

  const back = () => window.history.back();

  return { route, navigate, back };
}
