/* App router + mount — clean path URLs ( / · /about · /contact ) via History API.
   On Cloudflare Pages the _redirects SPA fallback serves index.html for every
   path, so deep links and refreshes work. */
const { useState: useStateA, useEffect: useEffectA, useCallback: useCallbackA } = React;

const ROUTES = ['home','about','contact'];

/* Route from the current path's last segment — works both on the deployed
   site (/about) and in preview where index.html sits in a subfolder. */
function routeFromPath(){
  const seg = (window.location.pathname.split('/').pop() || '').toLowerCase();
  const clean = seg.replace(/\.html?$/,'');
  return ROUTES.includes(clean) ? clean : 'home';
}

/* Build the URL for a route, preserving the folder index.html lives in so it
   also works when previewed from a subdirectory. */
function pathFor(id){
  const parts = window.location.pathname.split('/');
  parts.pop();                          // drop current last segment
  const base = parts.join('/') || '';
  return (base + '/' + (id === 'home' ? '' : id)) || '/';
}

function App(){
  const [route, setRoute] = useStateA(routeFromPath());

  const go = useCallbackA((id) => {
    if (id === route){ window.scrollTo({top:0, behavior:'smooth'}); return; }
    window.history.pushState({ id }, '', pathFor(id));
    setRoute(id);
    window.scrollTo({top:0, behavior:'auto'});
  }, [route]);

  useEffectA(() => {
    const onPop = () => { setRoute(routeFromPath()); window.scrollTo({top:0, behavior:'auto'}); };
    window.addEventListener('popstate', onPop);
    // migrate any legacy #/route links to a clean path
    const legacy = (window.location.hash || '').replace(/^#\/?/, '').trim();
    if (ROUTES.includes(legacy)){
      window.history.replaceState({ id: legacy }, '', pathFor(legacy));
      setRoute(legacy);
    }
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  useReveals(route);

  const View = route === 'about' ? About : route === 'contact' ? Contact : Home;
  return (
    <>
      <Nav route={route} go={go}/>
      <View go={go}/>
    </>
  );
}

/* expose a helper so links can render real href values */
window.pathFor = pathFor;

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