/* global React, ReactDOM, Navbar, Hero, Marquee, About, Experience, Projects, Skills, Contact, Footer */

/**
 * app.jsx
 *
 * Root of the React application. Responsibilities:
 *  1. Dark-mode state — initialized from localStorage, falls back to the
 *     OS preference via matchMedia("prefers-color-scheme: dark").
 *  2. Syncs the "dark" class on <html> and persists the choice to localStorage
 *     whenever the user toggles the theme via the Navbar button.
 *  3. Composes all section components into the page and passes dark/setDark
 *     down to Navbar so the toggle button has access to the state.
 *
 * This file is the last script loaded in index.html; by the time it runs,
 * all section components are already attached to window.*.
 */

const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  // Lazy initializer runs once — reads stored preference before first paint
  // to avoid a flash of the wrong theme.
  const [dark, setDark] = useStateApp(() => {
    const stored = localStorage.getItem("theme");
    if (stored === "dark")  return true;
    if (stored === "light") return false;
    // No stored preference — honour the OS setting
    return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  });

  // Keep the <html> class and localStorage in sync whenever dark changes.
  useEffectApp(() => {
    const root = document.documentElement;
    if (dark) root.classList.add("dark");
    else      root.classList.remove("dark");
    localStorage.setItem("theme", dark ? "dark" : "light");
  }, [dark]);

  return (
    <>
      <Navbar dark={dark} setDark={setDark} />
      <main>
        <Hero />
        <Marquee />
        <About />
        <Experience />
        <Projects />
        <Skills />
        <Contact />
      </main>
      <Footer />
    </>
  );
}

// Mount into the #root div defined in index.html
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
