// app.jsx — Erudity landing root.
// Theme resolution lives in the inline THEME_BOOTSTRAP (see src/templates.ts):
// it sets document.body.dataset.theme synchronously from saved choice or
// prefers-color-scheme before paint. We just mirror that into React state and
// only persist when the user explicitly toggles (otherwise OS-preference
// changes would stop applying after first render).

const { useEffect, useState, useRef } = React;

const THEME_KEY = 'erudity-theme';

function readInitialTheme() {
  return document.body.dataset.theme === 'dark' ? 'dark' : 'light';
}

function App() {
  const [theme, setTheme] = useState(readInitialTheme);
  const downloadRef = useRef(null);

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

  // Pick up live OS-preference changes dispatched by THEME_BOOTSTRAP
  // (only fires when no manual choice is saved in localStorage).
  useEffect(() => {
    const onOsChange = (e) => setTheme(e.detail === 'dark' ? 'dark' : 'light');
    window.addEventListener('erudity-theme-change', onOsChange);
    return () => window.removeEventListener('erudity-theme-change', onOsChange);
  }, []);

  const onToggleTheme = () => setTheme((t) => {
    const next = t === 'light' ? 'dark' : 'light';
    try { localStorage.setItem(THEME_KEY, next); } catch (_) {}
    return next;
  });
  const onJoin = () => {
    if (downloadRef.current) {
      const top = downloadRef.current.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  return (
    <>
      <Header theme={theme} onToggleTheme={onToggleTheme} onJoin={onJoin} />
      <Hero />
      <Roulette subjects={window.SUBJECTS} variant="slot" onJoin={onJoin} />
      <FlyingCards questions={window.QUESTIONS} />
      <Download ref={downloadRef} />
      <Footer />
    </>
  );
}

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