/* Shared shell for every page: theme + lang state, Nav, Footer, mountPage().
   Also: PAGES url map, PageHero (compact internal hero), CTABand. */

function langFromURL() {
  const m = window.location.pathname.match(/^\/(en|pt-br|pt)(\/|$)/);
  return m ? m[1] : null;
}

function getPAGES(lang) {
  return {
    home:    '/' + lang + '/',
    how:     '/' + lang + '/como-funciona',
    why:     '/' + lang + '/por-que-brasil',
    cases:   '/' + lang + '/cases',
    services:'/' + lang + '/servicos',
    about:   '/' + lang + '/sobre',
    contact: '/' + lang + '/contato',
    expand:  '/' + lang + '/expand-to-brazil',
  };
}

function usePrefs() {
  const [lang] = useState(() => {
    const url = langFromURL();
    if (url) return url;
    const s = localStorage.getItem('bne-lang');
    if (s && ['en','pt-br','pt'].includes(s)) return s;
    const n = (navigator.language || 'en').slice(0, 2);
    return n === 'pt' ? 'pt-br' : 'en';
  });
  const setLang = (l) => {
    localStorage.setItem('bne-lang', l);
    const cur = langFromURL() || 'en';
    const newPath = window.location.pathname.replace('/' + cur, '/' + l);
    window.location.href = newPath || '/' + l + '/';
  };
  const [theme, setTheme] = useState(() => {
    const s = localStorage.getItem('bne-theme'); if (s) return s;
    return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
  });
  useEffect(() => { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('bne-theme', theme); }, [theme]);
  useEffect(() => { localStorage.setItem('bne-lang', lang); document.documentElement.setAttribute('lang', lang === 'en' ? 'en' : 'pt-BR'); }, [lang]);
  return { lang, setLang, theme, setTheme };
}

/* Compact hero for internal pages. title supports \n line breaks. */
function PageHero({ data }) {
  return (
    <Section bg="deep" style={{ overflow:'hidden', background:'var(--deep-bg)' }} label="Page hero">
      <div aria-hidden="true" style={{ position:'absolute', inset:0, pointerEvents:'none',
        background:'radial-gradient(55% 70% at 82% 8%, rgba(123,47,190,.14), transparent 60%)' }}></div>
      <div aria-hidden="true" style={{ position:'absolute', inset:0, pointerEvents:'none', opacity:.5,
        backgroundImage:'linear-gradient(var(--deep-card) 1px, transparent 1px), linear-gradient(90deg, var(--deep-card) 1px, transparent 1px)',
        backgroundSize:'64px 64px', maskImage:'radial-gradient(70% 80% at 70% 20%, #000 20%, transparent 80%)',
        WebkitMaskImage:'radial-gradient(70% 80% at 70% 20%, #000 20%, transparent 80%)' }}></div>
      <Container style={{ position:'relative', paddingTop:168, paddingBottom:80, maxWidth:980 }}>
        <Reveal><Eyebrow style={{ marginBottom:20 }}>{data.eyebrow}</Eyebrow></Reveal>
        <Reveal delay={60}>
          <h1 className="t-display" style={{ margin:0, color:'var(--on-deep-1)', fontSize:'clamp(40px,5.6vw,76px)' }}>
            {data.title.split('\n').map((line,i) => <React.Fragment key={i}>{i>0 && <br/>}{line}</React.Fragment>)}
          </h1>
        </Reveal>
        <Reveal delay={120}>
          <p className="t-lead" style={{ color:'var(--on-deep-2)', marginTop:22, maxWidth:600 }}>{data.sub}</p>
        </Reveal>
      </Container>
    </Section>
  );
}

function CTABand({ t }) {
  return (
    <Section bg="deep" style={{ overflow:'hidden', background:'var(--deep-bg)' }} label="CTA">
      <div aria-hidden="true" style={{ position:'absolute', inset:0, pointerEvents:'none',
        background:'radial-gradient(60% 120% at 50% 0%, rgba(123,47,190,.12), transparent 60%)' }}></div>
      <Container style={{ position:'relative', paddingTop:88, paddingBottom:88, textAlign:'center' }}>
        <Reveal><div style={{ display:'inline-flex', marginBottom:22 }}><Mark size={40} variant="auto" /></div></Reveal>
        <Reveal delay={60}><h2 className="t-h1" style={{ margin:0, color:'var(--on-deep-1)', maxWidth:780, marginInline:'auto', textWrap:'balance' }}>{t.cta.title}</h2></Reveal>
        <Reveal delay={120}><p className="t-lead" style={{ color:'var(--on-deep-2)', marginTop:18, maxWidth:540, marginInline:'auto' }}>{t.cta.sub}</p></Reveal>
        <Reveal delay={180}>
          <div style={{ display:'flex', gap:14, justifyContent:'center', marginTop:32, flexWrap:'wrap' }}>
            <Button variant="solid" href={window.PAGES.contact}>{t.cta.primary}</Button>
            <Button variant="ghost" href={window.PAGES.cases}>{t.cta.secondary}</Button>
          </div>
        </Reveal>
        {t.cta.altText && <Reveal delay={220}>
          <a href={t.cta.altUrl} target="_blank" rel="noopener" style={{ display:'inline-flex', flexDirection:'column', gap:4, marginTop:22, textDecoration:'none', maxWidth:440, marginInline:'auto' }}>
            <span className="t-caption" style={{ color:'var(--on-deep-3)' }}>{t.cta.altText}</span>
            <span style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6, color:'var(--accent)', fontFamily:'var(--font-body)', fontWeight:600, fontSize:14.5 }}>{t.cta.altCta} <Icon name="arrow" size={15}/></span>
          </a>
        </Reveal>}
      </Container>
    </Section>
  );
}

/* Renders the full page: Nav + page content + CTA band (optional) + Footer. */
function mountPage(PageComponent, activeKey, opts) {
  opts = opts || {};
  const initLang = langFromURL() || localStorage.getItem('bne-lang') || 'en';
  window.PAGES = getPAGES(initLang);
  function App() {
    const { lang, setLang, theme, setTheme } = usePrefs();
    window.PAGES = getPAGES(lang);
    const t = window.BNE[lang] || window.BNE['pt'];
    return (
      <React.Fragment>
        <Nav t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} active={activeKey} heroDark={theme === 'dark'} />
        <main>
          <PageComponent t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
          {opts.cta !== false && <CTABand t={t} />}
        </main>
        <Footer t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
      </React.Fragment>
    );
  }
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
}

Object.assign(window, { langFromURL, getPAGES, PageHero, CTABand, mountPage, usePrefs });
