/* ============================================================
   Tectus — History API router. Uses pushState for clean URLs
   (no #). A global click interceptor converts all legacy
   href="#/route" links transparently — no link changes needed.
   Vercel's SPA rewrite sends every path to index.html so
   direct loads and back/forward navigation work correctly.
   ============================================================ */

function currentRoute() {
  /* If page was loaded with a legacy hash URL, read the hash */
  const h = window.location.hash || '';
  if (h.startsWith('#/')) {
    const r = h.slice(2).replace(/\/+$/, '');
    return r || '';
  }
  /* anchor-only hashes (#section) — treat as same-page, no route change */
  if (h.startsWith('#') && h.length > 1) return '__anchor__';
  /* normal pathname-based route */
  let p = window.location.pathname || '/';
  p = p.replace(/^\/+/, '').replace(/\/+$/, '');
  return p;
}

/* navigate to a route programmatically (used by the click interceptor) */
function navigate(route) {
  const url = route ? '/' + route : '/';
  history.pushState({ route }, '', url);
  window.dispatchEvent(new PopStateEvent('popstate', { state: { route } }));
}

/* intercept every click on a[href^="#/"] and convert to pushState */
document.addEventListener('click', function(e) {
  const a = e.target.closest('a[href]');
  if (!a) return;
  const href = a.getAttribute('href');
  if (!href || !href.startsWith('#/')) return;
  e.preventDefault();
  const route = href.slice(2).replace(/\/+$/, '');
  navigate(route);
}, true);

/* keep <link rel="canonical"> in sync */
function updateCanonical(route) {
  const link = document.querySelector('link[rel="canonical"]');
  if (!link) return;
  link.setAttribute('href', route ? 'https://tectusapp.com/' + route : 'https://tectusapp.com/');
}

function useRoute() {
  const [route, setRoute] = useState(function() {
    const r = currentRoute();
    /* on first load with a legacy #/ URL, swap to a clean URL silently */
    if (window.location.hash.startsWith('#/')) {
      const clean = r ? '/' + r : '/';
      history.replaceState({ route: r }, '', clean);
    }
    return r === '__anchor__' ? '' : r;
  });

  useEffect(function() { updateCanonical(route); }, []);

  useEffect(function() {
    function onPop() {
      const next = currentRoute();
      if (next === '__anchor__') return;
      setRoute(next);
      updateCanonical(next);
      window.scrollTo({ top: 0, behavior: 'auto' });
    }
    window.addEventListener('popstate', onPop);
    return function() { window.removeEventListener('popstate', onPop); };
  }, []);

  return route;
}

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