// App shell: theme toggle, router, page registry, eggs mount.

function App() {
  const route = useRoute();
  // Initial theme is set in index.html before first paint: the visitor's saved pick, else the OS.
  const [theme, setTheme] = React.useState(() => document.documentElement.dataset.theme);

  React.useEffect(() => {
    document.documentElement.dataset.theme = theme;
  }, [theme]);

  // Sudo mode's ribbon and status bar are CSS pseudo-elements; they read these with attr().
  React.useEffect(() => {
    document.body.dataset.buildInfo = buildRibbon();
    document.body.dataset.buildHash = BUILD ? BUILD.hash : 'local';
  }, []);

  React.useEffect(() => {
    const meta = pageMeta(route.path);
    document.title = meta ? meta.title : `Not found — ${SITE.author}`;
  }, [route.path]);

  // Only an explicit toggle is remembered, so visitors who never toggle keep following the OS.
  function toggleTheme() {
    const next = theme === 'light' ? 'dark' : 'light';
    try { localStorage.setItem('theme', next); } catch (e) {}
    setTheme(next);
  }

  return (
    <div className="shell">
      <Nav route={route} onTheme={toggleTheme} />
      <main style={{ flex: 1 }}>
        <PageBody route={route} />
      </main>
      <Foot />
      <EasterEggs />
    </div>
  );
}

function PageBody({ route }) {
  const path = route.path;
  if (path === '/' || path === '') return <HomePage route={route} />;
  if (path === '/writing') return <WritingPage route={route} />;
  if (route.segments[0] === 'writing' && route.segments[1]) return <PostPage route={route} />;
  if (route.segments[0] === 'experience' && route.segments[1]) return <ProjectPage route={route} />;
  if (path === '/about') return <AboutPage route={route} />;
  if (path === '/papers') return <PapersPage route={route} />;
  return <NotFoundPage route={route} />;
}

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