// router.jsx — minimal hash router for ruuapi landing
// Routes: '/' (home, VariantC) · '/pricing' · '/docs' · '/contact'
// Reads window.location.hash, normalizes to a path, re-renders on hashchange.
// Anchor in-page (#features etc.) still works because we only switch routes
// when the hash STARTS WITH '#/'.

function parseRoute() {
  const h = window.location.hash || '';
  if (!h.startsWith('#/')) return { path: '/', anchor: h.replace(/^#/, '') };
  // '#/pricing' -> '/pricing'   '#/pricing/faq' -> '/pricing/faq'
  return { path: h.slice(1) || '/', anchor: '' };
}

function useRoute() {
  const [route, setRoute] = React.useState(parseRoute);
  React.useEffect(() => {
    function onHash() {
      setRoute(parseRoute());
      // If the new hash includes an in-page anchor, scroll to it after paint.
      const r = parseRoute();
      if (r.anchor) {
        requestAnimationFrame(() => {
          const el = document.getElementById(r.anchor);
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });
      } else {
        window.scrollTo({ top: 0, behavior: 'instant' });
      }
    }
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function navigate(to) {
  // 'to' starts with '/' — convert to '#/...'
  window.location.hash = '#' + to;
}

Object.assign(window, { useRoute, navigate, parseRoute });
