// App composition + hash-based routing (#/signin → SignIn page; otherwise the home page)
const { useEffect: useEffectA, useState: useStateApp } = React;

function useHashRoute(){
  const [hash, setHash] = useStateApp(()=> window.location.hash || '');
  useEffectA(()=>{
    const onHash = ()=> setHash(window.location.hash || '');
    window.addEventListener('hashchange', onHash);
    return ()=> window.removeEventListener('hashchange', onHash);
  },[]);
  return hash;
}

function HomePage(){
  // Auto-reveal: every <section> heading + .eyebrow inside main fades up on enter.
  useEffectA(()=>{
    const targets = document.querySelectorAll('main section h2, main section .eyebrow, main section > .container > p');
    targets.forEach(el => el.classList.add('reveal'));
    const io = new IntersectionObserver((entries)=>{
      entries.forEach(e => {
        if (e.isIntersecting){
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, {threshold:0.15, rootMargin:'0px 0px -40px 0px'});
    targets.forEach(el => io.observe(el));
    return ()=>io.disconnect();
  },[]);

  return (
    <>
      <ScrollProgress/>
      <Nav/>
      <CursorCompanion/>
      <main style={{position:'relative',zIndex:1}}>
        <Hero/>
        <SignalTicker/>
        <MondayBrief/>
        <AlwaysOn/>
        <Handover/>
        <Memory/>
        <EvidenceBridge/>
        <Integrations/>
        <Security/>
        <CTA/>
        <Footer/>
      </main>
    </>
  );
}

function App(){
  const route = useHashRoute();

  useEffectA(()=>{
    const sp = document.getElementById('splash');
    if (sp){
      requestAnimationFrame(()=>{
        requestAnimationFrame(()=>{
          sp.classList.add('hide');
          setTimeout(()=>sp.classList.add('gone'), 800);
        });
      });
    }
  },[]);

  // Per-route title + meta description — updates browser tab + social previews on hash change.
  useEffectA(()=>{
    const META = {
      home:                 { title:'Nautilida — AI Team Lead for Sales',
                              desc:'Revenue memory. The AI team lead for sales — coordinates the team across your stack, tracks every signal, automates follow-through.' },
      '#/about':            { title:'About · Nautilida',
                              desc:'A small team in Berlin building Nauti — the AI team lead for sales. Anonymous on purpose, until we ship.' },
      '#/blog':             { title:'Blog · Notes from the lab — Nautilida',
                              desc:'Field notes from building Nauti. Manifestos, memory, and the engineering behind a quiet Monday brief.' },
      '#/blog/weekly-loop': { title:'The weekly revenue coordination loop, explained · Nautilida',
                              desc:'How an AI team lead coordinates your week — Monday brief, mid-week priorities, Friday recap, compounding memory.' },
      '#/blog/ai-team-lead':{ title:'What is an AI team lead for sales? · Nautilida',
                              desc:'Your next hire could be Nauti — AI team lead for sales. No coffee. No sleep. Perfect recall.' },
      '#/waitlist':         { title:'Join the waitlist · Nautilida',
                              desc:'Get early access to Nauti. Connect HubSpot and Teams in 12 minutes. First Monday brief lands at 7:00 AM.' },
      '#/contact':          { title:'Contact · Nautilida',
                              desc:'Talk to a human. Schedule a demo, pitch a topic, or just say hi. We reply fast.' },
      '#/signin':           { title:'Sign in · Nautilida',
                              desc:'Sign in to your Nautilida workspace.' },
      '#/privacy':          { title:'Privacy Policy · Nautilida',
                              desc:'How we collect, use, and protect your information. Privacy is a feature, not an afterthought.' },
      '#/terms':            { title:'Terms of Service · Nautilida',
                              desc:'The rules and regulations for using Nautilida.' },
    };
    const m = META[route] || META.home;
    document.title = m.title;
    const set = (sel, val)=>{
      const el = document.querySelector(sel);
      if (el) el.setAttribute('content', val);
    };
    set('meta[name="description"]',         m.desc);
    set('meta[property="og:title"]',        m.title);
    set('meta[property="og:description"]',  m.desc);
    set('meta[name="twitter:title"]',       m.title);
    set('meta[name="twitter:description"]', m.desc);

    // Google Analytics page_view — SPA hash routing doesn't trigger gtag automatically.
    if (typeof window.gtag === 'function'){
      window.gtag('event', 'page_view', {
        page_title: m.title,
        page_location: window.location.href,
        page_path: route || '/',
      });
    }
  }, [route]);

  // Reset scroll when route changes — but for section anchors (#product, #rhythm…)
  // smooth-scroll to the section instead of jumping to top. Offset for the fixed nav.
  useEffectA(()=>{
    const sectionAnchors = ['#product','#rhythm','#evidence','#integrations','#security','#pricing'];
    if (sectionAnchors.includes(route)){
      // Wait a tick so the home page is rendered if we just came from a sub-route.
      setTimeout(()=>{
        const el = document.querySelector(route);
        if (!el) {
          console.log('Element not found:', route);
          return;
        }
        const rect = el.getBoundingClientRect();
        const top = window.scrollY + rect.top - 130;
        console.log('Scroll to', route, 'offset:', top, 'rect.top:', rect.top, 'scrollY:', window.scrollY);
        window.scrollTo({top, behavior:'smooth'});
      }, 100);
      return;
    }
    window.scrollTo(0,0);
  }, [route]);

  const isSignIn   = route === '#/signin'   || route === '#signin';
  const isWaitlist = route === '#/waitlist' || route === '#waitlist';
  const isContact  = route === '#/contact'  || route === '#contact';
  const isAbout    = route === '#/about'    || route === '#about';
  const isPrivacy  = route === '#/privacy'  || route === '#privacy';
  const isTerms    = route === '#/terms'    || route === '#terms';
  const isBlog            = route === '#/blog'              || route === '#blog';
  const isPostWeeklyLoop  = route === '#/blog/weekly-loop';
  const isPostAITeamLead  = route === '#/blog/ai-team-lead';

  let page;
  if (isSignIn)               page = <SignIn/>;
  else if (isWaitlist)        page = <Waitlist/>;
  else if (isContact)         page = <Contact/>;
  else if (isAbout)           page = <About/>;
  else if (isPrivacy)         page = <Legal initialTab="privacy"/>;
  else if (isTerms)           page = <Legal initialTab="terms"/>;
  else if (isPostWeeklyLoop)  page = <PostWeeklyLoop/>;
  else if (isPostAITeamLead)  page = <PostAITeamLead/>;
  else if (isBlog)            page = <Blog/>;
  else                        page = <HomePage/>;

  return page;
}

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