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

function TabWrap({ children }) {
  return <div style={{ animation: 'fadeIn .35s ease' }}>{children}</div>;
}

function App() {
  const [tab, setTab] = useStateApp(() => {
    try { return localStorage.getItem('crius_tab_v2') || 'home'; } catch (e) { return 'home'; }
  });

  useEffectApp(() => {
    try { localStorage.setItem('crius_tab_v2', tab); } catch (e) {}
    window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
    window.__setTab = setTab;
  }, [tab]);

  // nav border appears once scrolled
  useEffectApp(() => {
    const nav = document.querySelector('.nav');
    const onScroll = () => { if (nav) nav.classList.toggle('scrolled', window.scrollY > 8); };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // subtle scroll-reveal, re-armed on every tab change
  useEffectApp(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!('IntersectionObserver' in window)) {
      els.forEach((e) => e.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.05 });
    els.forEach((e) => io.observe(e));
    return () => io.disconnect();
  }, [tab]);

  let content = null;
  if (tab === 'home') {
    content = (
      <TabWrap>
        <Hero />
        <LogoStrip />
        <PhotoBand id="photo-cork-harbour" caption="Cork Harbour, Ireland" />
        <CTASection />
      </TabWrap>
    );
  } else if (tab === 'approach') {
    content = (
      <TabWrap>
        <Approach />
      </TabWrap>
    );
  } else if (tab === 'lifesciences') {
    content = (
      <TabWrap>
        <LifeSciences />
        <CTASection />
      </TabWrap>
    );
  } else if (tab === 'trust') {
    content = (
      <TabWrap>
        <TrustValues />
      </TabWrap>
    );
  } else if (tab === 'about') {
    content = (
      <TabWrap>
        <About />
        <FAQ />
        <CTASection />
      </TabWrap>
    );
  } else if (tab === 'contact') {
    content = (
      <TabWrap>
        <DemoForm />
      </TabWrap>
    );
  } else {
    content = (
      <TabWrap>
        <Hero />
        <LogoStrip />
        <PhotoBand id="photo-cork-harbour" caption="Cork Harbour, Ireland" />
        <CTASection />
      </TabWrap>
    );
  }

  return (
    <React.Fragment>
      <Nav tab={tab} setTab={setTab} />
      {content}
      <Footer setTab={setTab} />
    </React.Fragment>
  );
}

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