/* ====================================================================
   app.jsx — shell: language state, scroll-spy, smooth nav.
   ==================================================================== */
function App() {
  const [lang, setLang] = useState(() => localStorage.getItem("mas-lang") || "en");
  const [active, setActive] = useState("home");
  const ids = ["home", "expertise", "work", "experience", "contact"];

  useEffect(() => {
    localStorage.setItem("mas-lang", lang);
    document.documentElement.lang = lang;
  }, [lang]);

  // scroll-spy
  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActive(e.target.id);
        });
      },
      { rootMargin: "-45% 0px -45% 0px", threshold: 0 }
    );
    ids.forEach((id) => {
      const el = document.getElementById(id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);

  // smooth scroll without scrollIntoView
  const onNav = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY;
      window.scrollTo({ top, behavior: "smooth" });
      history.replaceState(null, "", "#" + id);
      setActive(id);
    }
  };

  return (
    <div className="layout">
      <SideNav lang={lang} setLang={setLang} active={active} onNav={onNav} />
      <main className="main">
        <Hero lang={lang} onNav={onNav} />
        <Expertise lang={lang} />
        <Work lang={lang} />
        <Experience lang={lang} />
        <Contact lang={lang} />
      </main>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
