/* global React, ReactDOM, Header, Footer,
   HomePage, PortfolioPage, AboutPage, InvestmentPage, JournalPage, ContactPage,
   GalleryPage, JournalPostPage, PageFade */

const { useState, useEffect } = React;

const PAGES = {
  home:       HomePage,
  portfolio:  PortfolioPage,
  about:      AboutPage,
  investment: InvestmentPage,
  journal:    JournalPage,
  contact:    ContactPage,
  gallery:    GalleryPage,      // #gallery/<slug>
  post:       JournalPostPage,  // #post/<n>
};

/* Detail pages highlight their parent section in the nav */
const NAV_PARENT = { gallery: 'portfolio', post: 'journal' };

/* Hash routing so reloads land on the same page.
   Supports an optional param segment: #gallery/weddings, #post/03 */
function parseRoute() {
  const raw = (window.location.hash || '#home').replace(/^#/, '');
  const [id, ...rest] = raw.split('/');
  return PAGES[id] ? { id, param: rest.join('/') || null } : { id: 'home', param: null };
}

function App() {
  const [route, setRoute] = useState(parseRoute);

  const nav = (target) => {
    window.location.hash = target;
    setRoute(parseRoute());
  };

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

  /* Every route change starts at the top of the new page.
     This lives in an effect rather than in nav() for three reasons:
       · it runs AFTER the new page has committed, so the browser is not still
         clamping the scroll offset against the old page's height;
       · it also covers arriving via hashchange — the back/forward buttons and
         any bare #link — which nav() never sees;
       · on mobile the drawer sets body{overflow:hidden}, and scrolling a frozen
         body is a no-op. By the time effects run the drawer has released it.
     Instant, not smooth: a smooth scroll from the foot of a long page gets
     cancelled the moment the incoming page changes the document height. */
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [route.id, route.param]);

  const Current = PAGES[route.id] || HomePage;

  return (
    <div className="kit-page">
      <Header activePage={NAV_PARENT[route.id] || route.id} onNav={nav} />
      <main>
        <PageFade k={route.id + (route.param || '')}>
          <Current onNav={nav} param={route.param} />
        </PageFade>
      </main>
      <Footer onNav={nav} />
    </div>
  );
}

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