/* ===================================================
   APP SHELL — SPA router
   Persistent <Nav> and <Footer> stay mounted across
   route changes; only the page content swaps.
   =================================================== */

function getRoute() {
  const path = window.location.pathname;
  if (path.endsWith('repo.html') || path.endsWith('/repo'))  return { name: 'repo' };
  const autorMatch = path.match(/\/autor\/([^/]+)/);
  if (autorMatch) return { name: 'author', authorId: autorMatch[1] };
  if (path.endsWith('autor.html')) {
    const id = new URLSearchParams(window.location.search).get('id');
    return { name: 'author', authorId: id || undefined };
  }
  return { name: 'home' };
}

function App() {
  const [route, setRoute] = React.useState(getRoute());
  const [phase, setPhase] = React.useState('in'); // 'in' | 'out'
  const [pendingRoute, setPendingRoute] = React.useState(null);

  // listen to browser navigation events
  React.useEffect(() => {
    const onPop = () => setRoute(getRoute());
    window.addEventListener('popstate', onPop);

    // intercept TransitionLink navigation
    const onSpaNav = (e) => {
      const href = e.detail.href;
      window.history.pushState({}, '', href);
      const next = getRoute();
      // animate out, then swap, then animate in
      setPhase('out');
      setPendingRoute(next);
    };
    window.addEventListener('spa:navigate', onSpaNav);

    return () => {
      window.removeEventListener('popstate', onPop);
      window.removeEventListener('spa:navigate', onSpaNav);
    };
  }, []);

  // when 'out' animation finishes, swap route + scroll top + animate in
  React.useEffect(() => {
    if (phase !== 'out' || !pendingRoute) return;
    const t = setTimeout(() => {
      setRoute(pendingRoute);
      setPendingRoute(null);
      window.scrollTo({ top: 0, behavior: 'instant' });
      // next tick → in
      requestAnimationFrame(() => requestAnimationFrame(() => setPhase('in')));
    }, 220);
    return () => clearTimeout(t);
  }, [phase, pendingRoute]);

  let active = null;
  if (route.name === 'home') active = 'home';
  if (route.name === 'repo') active = 'repo';

  return (
    <>
      <FlashlightGlow />
      <Nav active={active} />

      <div className={"page-content " + (phase === 'out' ? 'is-leaving' : '')}>
        {route.name === 'home'   && <HomeApp />}
        {route.name === 'repo'   && <RepoApp />}
        {route.name === 'author' && <AuthorApp routeAuthorId={route.authorId} />}
      </div>

      <Footer />
    </>
  );
}

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