// VibeAlchemy Marketing · App root with hash routing + theme toggle

// Same key as the React app (ui/src/main.jsx) so theme carries between
// marketing ↔ /app without re-prompting the user.
const THEME_STORAGE_KEY = 'va_theme';
// Legacy key from the marketing prototype — read once for back-compat,
// then write through to the unified key.
const LEGACY_KEY = 'va-marketing-theme';

function readInitialTheme() {
  try {
    const stored = localStorage.getItem(THEME_STORAGE_KEY)
      || localStorage.getItem(LEGACY_KEY);
    if (stored === 'dark' || stored === 'light') return stored;
  } catch (_) {}
  return 'dark';
}

function App() {
  const route = useRoute();
  const [theme, setTheme] = useState(readInitialTheme);

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    document.documentElement.setAttribute('data-grain', '1');
    try { localStorage.setItem(THEME_STORAGE_KEY, theme); } catch (_) {}
  }, [theme]);

  const toggleTheme = () => setTheme((t) => (t === 'dark' ? 'light' : 'dark'));

  let page;
  if (route === '/' || route === '') page = <LandingPage />;
  else if (route === '/how-it-works') page = <HowItWorksPage />;
  else if (route === '/pricing') page = <PricingPage />;
  else if (route === '/examples') page = <ExamplesPage />;
  else if (route.startsWith('/examples/')) page = <ExampleDetailPage slug={route.replace('/examples/', '')} />;
  else if (route === '/about') page = <AboutPage />;
  else if (route === '/faq') page = <FAQPage />;
  else if (route === '/for-founders') page = <ForFoundersPage />;
  else if (route === '/for-all-in') page = <ForAllInPage />;
  else if (route.startsWith('/compare/')) page = <ComparePage slug={route.replace('/compare/', '')} />;
  else if (route === '/changelog') page = <ChangelogPage />;
  else if (route === '/roadmap') page = <RoadmapPage />;
  else if (route === '/contact') page = <ContactPage />;
  else page = <LandingPage />;

  return (
    <div className="va-grain" style={{ minHeight: '100vh' }}>
      <TopNav route={route} theme={theme} onToggleTheme={toggleTheme} />
      {page}
      <Footer />
      <WaitlistRoot />
    </div>
  );
}

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