// app.jsx - hash router + view + overlay state
const { useState: useStateA, useEffect: useEffectA } = React;

function parseHash() {
  let h = (window.location.hash || '').replace(/^#/, '');
  if (!h || h === '/') return { view: 'home' };
  const parts = h.split('/').filter(Boolean); // ['work'] | ['work','id'] | ['about']
  if (parts[0] === 'work' && parts[1]) return { view: 'case', id: parts[1] };
  if (parts[0] === 'work') return { view: 'work' };
  if (parts[0] === 'about') return { view: 'about' };
  return { view: 'home' };
}

function App() {
  const [route, setRoute] = useStateA(parseHash());
  const [contact, setContact] = useStateA(false);
  const [toast, setToast] = useStateA(null);

  useEffectA(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // scroll to top on view/id change
  useEffectA(() => { window.scrollTo({ top: 0 }); }, [route.view, route.id]);

  const go = (path) => {
    const target = '#' + (path.startsWith('/') ? path : '/' + path);
    if (window.location.hash === target) { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    window.location.hash = target;
  };
  const onContact = () => setContact(true);
  const onResume = () => setToast('Résumé PDF coming soon. Email me for the latest copy.');

  const project = route.view === 'case' ? PROJECTS.find(p => p.id === route.id) : null;
  if (route.view === 'case' && !project) { // unknown id → work index
    return <Redirect to="/work" go={go} />;
  }

  let section = '';
  let subLabel = 'Engineer-builder';
  if (route.view === 'work') { section = 'work'; subLabel = 'Selected work'; }
  else if (route.view === 'case') { section = 'work'; subLabel = project.name; }
  else if (route.view === 'about') { section = 'about'; subLabel = 'About'; }

  return (
    <div>
      <GlobalNav go={go} section={section} />
      <SubNav label={subLabel} go={go} onContact={onContact} onResume={onResume} />
      {route.view === 'home' && <Home go={go} onContact={onContact} onResume={onResume} />}
      {route.view === 'work' && <WorkIndex go={go} />}
      {route.view === 'case' && <CaseStudy p={project} go={go} onContact={onContact} />}
      {route.view === 'about' && <AboutPage go={go} onContact={onContact} onResume={onResume} />}
      <Footer go={go} onContact={onContact} onResume={onResume} />
      <ContactSheet open={contact} onClose={() => setContact(false)} onResume={onResume} />
      <Toast msg={toast} onDone={() => setToast(null)} />
    </div>
  );
}

function Redirect({ to, go }) {
  useEffectA(() => { go(to); }, []);
  return null;
}

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