// site/site.jsx — routeur hash + langue (FR/EN/DE) + scroll reveal.

const { useState: useStateR, useEffect: useEffectR } = React;

const I18N = { fr: window.L_FR, en: window.L_EN, de: window.L_DE };

function Site() {
  const initial = (typeof location !== 'undefined' && location.hash.replace('#', '')) || 'home';
  const [page, setPage] = useStateR(initial);
  const [lang, setLangState] = useStateR(() => {
    try { return localStorage.getItem('calinange-lang') || 'fr'; } catch (e) { return 'fr'; }
  });
  const L = I18N[lang] || I18N.fr;

  const setLang = (id) => {
    setLangState(id);
    try { localStorage.setItem('calinange-lang', id); } catch (e) {}
  };

  useEffectR(() => { document.documentElement.lang = lang; }, [lang]);

  const go = (id) => {
    setPage(id);
    if (typeof location !== 'undefined') location.hash = id;
    if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'auto' });
  };

  useEffectR(() => {
    const onHash = () => setPage(location.hash.replace('#', '') || 'home');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Révélation douce des sections au scroll (sauf la première, qui a sa propre entrée).
  useEffectR(() => {
    const sections = Array.from(document.querySelectorAll('main section')).slice(1);
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('rv-in');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.05 });
    sections.forEach(s => { s.classList.add('rv'); io.observe(s); });
    return () => io.disconnect();
  }, [page, lang]);

  const pages = {
    home:      <HomePage      go={go} L={L} />,
    about:     <AboutPage     go={go} L={L} />,
    who:       <WhoPage       go={go} L={L} />,
    charter:   <CharterPage   go={go} L={L} />,
    volunteer: <VolunteerPage go={go} L={L} />,
    donate:    <DonatePage    go={go} L={L} />,
    contact:   <ContactPage   go={go} L={L} />,
  };

  return (
    <div>
      <Nav current={page} go={go} L={L} lang={lang} setLang={setLang} />
      <main key={page + '-' + lang}>{pages[page] || pages.home}</main>
      <Footer go={go} L={L} />
    </div>
  );
}

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