/* kada-spa.jsx — hash router that hosts all pages in one document.
   Page components register themselves on window.__KADA_PAGES.
   Routes: "#base" or "#base/param" (param drives detail pages).
   entry.active may be a string or a fn(param) → nav key to highlight. */

const FILE2KEY = Object.fromEntries(KSITE.nav.map((n) => [n.href, n.key]));

function KadaSPA() {
  const parse = () => {
    const raw = decodeURIComponent(location.hash.replace(/^#\/?/, ''));
    const [base, ...rest] = raw.split('/');
    const known = window.__KADA_PAGES && window.__KADA_PAGES[base];
    return { base: known ? base : 'home', param: rest.join('/') || null };
  };
  const [route, setRoute] = React.useState(parse);

  React.useEffect(() => {
    const onHash = () => { setRoute(parse()); window.scrollTo({ top: 0, left: 0 }); };
    window.addEventListener('hashchange', onHash);
    const onClick = (e) => {
      const a = e.target.closest && e.target.closest('a');
      if (!a) return;
      const href = a.getAttribute('href');
      if (!href) return;
      if (href === '#') { e.preventDefault(); return; }
      const key = FILE2KEY[href];
      if (key != null) {
        e.preventDefault();
        if (location.hash.replace(/^#\/?/, '') === key) window.scrollTo({ top: 0, left: 0 });
        else location.hash = '#' + key;
      }
    };
    document.addEventListener('click', onClick);
    return () => { window.removeEventListener('hashchange', onHash); document.removeEventListener('click', onClick); };
  }, []);

  const entry = window.__KADA_PAGES[route.base] || window.__KADA_PAGES.home;
  const Comp = entry.Comp;
  const active = typeof entry.active === 'function' ? entry.active(route.param) : entry.active;
  return (
    <div className="ka-route" key={route.base + (route.param || '')}>
      <KadaPage active={active}><Comp routeParam={route.param} /></KadaPage>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<KadaSPA />);
