// Minimal dependency-free hash router. Hash routing survives a reload and works on
// a file:// origin (Capacitor native packaging), where there is no server to honour
// deep paths. The route is a reactive rune so screens re-render on navigation. The pure
// hash->Route parsing lives in routeparse.ts (unit-tested without a DOM).

import { parse, type Route, type RouteName } from './routeparse';

export type { Route, RouteName };

export const router = $state<{ route: Route }>({
  route: parse(typeof location !== 'undefined' ? location.hash : ''),
});

if (typeof window !== 'undefined') {
  window.addEventListener('hashchange', () => {
    router.route = parse(location.hash);
  });
}

/** navigate switches the hash route (and forces a re-parse if it is unchanged). */
export function navigate(path: string): void {
  const target = '#' + path;
  if (location.hash === target) {
    router.route = parse(target);
  } else {
    location.hash = path;
  }
}
