// Main app — wires together sections + lightbox + scroll-spy
const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [active, setActive] = useStateApp('top');
  const [openProject, setOpenProject] = useStateApp(null);

  // Scroll-spy
  useEffectApp(() => {
    const sections = ['top', 'about', 'sustainability', 'projects', 'contact'];
    const onScroll = () => {
      const y = window.scrollY + window.innerHeight * 0.35;
      let cur = 'top';
      for (const id of sections) {
        const el = id === 'top' ? document.body : document.getElementById(id);
        if (!el) continue;
        const top = id === 'top' ? 0 : el.offsetTop;
        if (y >= top) cur = id;
      }
      setActive(cur);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Hash-based deep links e.g. #project/shwasam
  useEffectApp(() => {
    const handleHash = () => {
      const h = window.location.hash;
      const m = h.match(/^#project\/(.+)$/);
      if (m) {
        setOpenProject(m[1]);
      } else if (h && h !== '#') {
        const id = h.slice(1);
        const el = document.getElementById(id);
        if (el) el.scrollIntoView ? null : null;
      }
    };
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, []);

  const navigateTo = (id) => {
    if (id === 'top') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  const openProjectFn = (id) => {
    setOpenProject(id);
    window.history.replaceState(null, '', `#project/${id}`);
  };
  const closeProject = () => {
    setOpenProject(null);
    window.history.replaceState(null, '', '#projects');
  };

  return (
    <React.Fragment>
      <window.Nav activeSection={active} onNavigate={navigateTo} />
      <window.Hero onNavigate={navigateTo} />
      <window.About />
      <window.Sustainability />
      <window.Projects onOpen={openProjectFn} />
      <window.Instagram />
      <window.Contact />
      <window.Footer onNavigate={navigateTo} />
      <window.Lightbox projectId={openProject} onClose={closeProject} onSelect={openProjectFn} />
    </React.Fragment>
  );
}

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