/* =========================================================================
   PRESENÇA — shared runtime (components used across all pages)
   Exposes globals on window for the per-page scripts to consume.
   ========================================================================= */
const { useState, useEffect, useRef } = React;
const CFG = window.SITE_CONFIG;
const C = window.SITE_CONTENT;
const NAV = window.SITE_NAV;

const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const isTouch = window.matchMedia('(hover: none), (pointer: coarse)').matches;

/* ---------------------------------------------------------------- whatsapp */
function waLink(customMsg) {
  const msg = encodeURIComponent(customMsg || CFG.whatsappMsg);
  return `https://wa.me/${CFG.whatsappNumber}?text=${msg}`;
}

/* ---------------------------------------------------------------- icons */
function WhatsAppIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M.057 24l1.687-6.163a11.867 11.867 0 01-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.82 11.82 0 018.413 3.488 11.82 11.82 0 013.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 01-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 001.51 5.26l-.999 3.648 3.978-1.087zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z" />
    </svg>);

}

/* ---------------------------------------------------------------- AURA (Change 2) */
function Aura() {
  const ref = useRef(null);
  useEffect(() => {
    if (isTouch || prefersReduced) return;
    let tx = innerWidth * 0.85,ty = innerHeight * 0.9,cx = tx,cy = ty,raf;
    const onMove = (e) => {tx = e.clientX;ty = e.clientY;};
    const loop = () => {
      cx += (tx - cx) * 0.08;
      cy += (ty - cy) * 0.08;
      if (ref.current) ref.current.style.transform = `translate(${cx - 300}px, ${cy - 300}px)`;
      raf = requestAnimationFrame(loop);
    };
    window.addEventListener('mousemove', onMove, { passive: true });
    loop();
    return () => {cancelAnimationFrame(raf);window.removeEventListener('mousemove', onMove);};
  }, []);
  if (isTouch || prefersReduced) return null;
  return <div ref={ref} className="aura-glow" aria-hidden="true"></div>;
}

/* ---------------------------------------------------------------- BACKGROUND WORDS
   Static, in-document decorative words. Scroll with content, no cursor/aura
   dependency. Always faintly visible; the aura adds a slight highlight where
   it happens to overlap. Hidden on mobile. */
const BG_SIZES = [
{ size: 'clamp(7rem, 16vw, 12rem)', rot: '-4deg' },
{ size: 'clamp(6rem, 13vw, 10rem)', rot: '3deg' },
{ size: 'clamp(8rem, 18vw, 14rem)', rot: '-2deg' },
{ size: 'clamp(7rem, 15vw, 11rem)', rot: '5deg' },
{ size: 'clamp(8rem, 17vw, 13rem)', rot: '-3deg' },
{ size: 'clamp(9rem, 19vw, 15rem)', rot: '-6deg' }];


function BackgroundWords({ words }) {
  const list = (words && words.length ? words : ['TREINO', 'PRESENÇA', 'FORÇA', 'MÉTODO', 'EVOLUÇÃO', 'FOCO']).slice(0, 6);
  return (
    <div className="background-words" aria-hidden="true">
      {list.map((w, i) =>
      <span key={i} className="bg-word"
      style={{ fontSize: BG_SIZES[i % BG_SIZES.length].size, transform: `rotate(${BG_SIZES[i % BG_SIZES.length].rot})` }}>
          {w}
        </span>
      )}
    </div>);

}

/* ---------------------------------------------------------------- HEADER (Change 5) */
function Header({ active }) {
  const [stuck, setStuck] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setStuck(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
  }, [open]);

  return (
    <React.Fragment>
      <nav className={'nav' + (stuck ? ' is-stuck' : '')}>
        <a className="nav__brand" href="index.html" aria-label={CFG.brand + ' — início'}>
          <span className="nav__dot"></span>{CFG.brand}
        </a>
        <div className="nav__links">
          {NAV.map((n) =>
          <a key={n.id} className={'nav__link' + (n.id === active ? ' is-active' : '')}
          href={n.href} aria-current={n.id === active ? 'page' : undefined}>
              {n.label}
            </a>
          )}
        </div>
        <a className="nav__cta" href={waLink()} target="_blank" rel="noopener">Agendar</a>
        <button className="nav__burger" aria-label="Abrir menu" aria-expanded={open} onClick={() => setOpen(true)}>
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
            <line x1="3" y1="7" x2="21" y2="7" /><line x1="3" y1="13" x2="21" y2="13" /><line x1="3" y1="19" x2="15" y2="19" />
          </svg>
        </button>
      </nav>

      <div className={'navmenu' + (open ? ' is-open' : '')} aria-hidden={!open}>
        <div className="navmenu__top">
          <span className="nav__brand"><span className="nav__dot"></span>{CFG.brand}</span>
          <button className="nav__burger" aria-label="Fechar menu" onClick={() => setOpen(false)} style={{ display: 'inline-flex' }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
              <line x1="5" y1="5" x2="19" y2="19" /><line x1="19" y1="5" x2="5" y2="19" />
            </svg>
          </button>
        </div>
        <div className="navmenu__links">
          {NAV.map((n, i) =>
          <a key={n.id} className={'navmenu__link' + (n.id === active ? ' is-active' : '')} href={n.href}>
              <span className="i">0{i + 1}</span>{n.label}
            </a>
          )}
        </div>
      </div>
    </React.Fragment>);

}

/* ---------------------------------------------------------------- WhatsApp CTA */
function WhatsAppButton({ label, msg, small }) {
  return (
    <a className={'btn-wa' + (small ? ' btn-wa--sm' : '')} href={waLink(msg)} target="_blank" rel="noopener">
      <WhatsAppIcon /> {label}
    </a>);

}

/* shared CTA band used at the foot of internal pages */
function CtaBand() {
  const k = C.ctaBlock;
  return (
    <section className="section cta-band">
      <div className="shell">
        <span className="kicker reveal" style={{ marginInline: 'auto', justifyContent: 'center' }}>{k.kicker}</span>
        <h2 className="h-section reveal" data-d="1" style={{ marginTop: 14 }}>{k.headline}</h2>
        <p className="lead reveal" data-d="1" style={{ marginInline: 'auto', marginTop: 22, textAlign: 'center' }}>{k.lead}</p>
        <div className="reveal" data-d="2"><WhatsAppButton label={k.button} /></div>
      </div>
    </section>);

}

/* ---------------------------------------------------------------- FOOTER (Change 5) */
function Footer() {
  return (
    <footer className="footer">
      <span className="footer__brand"><span className="nav__dot"></span>{CFG.brand}</span>
      <div className="footer__links">
        <a href={waLink()} target="_blank" rel="noopener">WhatsApp</a>
        <a href="#" target="_blank" rel="noopener">{CFG.contact.instagram}</a>
        <a href={'mailto:' + CFG.contact.email}>{CFG.contact.email}</a>
      </div>
      <span className="footer__c">© 2026 {CFG.firstName} {CFG.lastName} · {CFG.city}</span>
    </footer>);

}

/* ---------------------------------------------------------------- quote card */
function QuoteCard({ q }) {
  return (
    <blockquote className="quote card-glass">
      <div className="quote__mark" aria-hidden="true">”</div>
      <p className="quote__text">{q.text}</p>
      <div>
        <div className="quote__name">{q.name}</div>
        <div className="quote__meta">{q.meta}</div>
      </div>
    </blockquote>);

}

/* ---------------------------------------------------------------- page hero (internal) */
function PageHero({ title, intro }) {
  return (
    <header className="pagehero">
      <div className="hero__grid" aria-hidden="true"></div>
      <div className="shell" style={{ position: 'relative', zIndex: 2 }}>
        <h1 className="pagehero__title reveal" style={{ fontSize: "82px" }}>{title}</h1>
        <p className="lead pagehero__intro reveal" data-d="1">{intro}</p>
      </div>
    </header>);

}

/* ---------------------------------------------------------------- theme + reveal + mount */
function applyTheme(t) {
  const root = document.documentElement.style;
  const acc = CFG.accents.find((a) => a.main === (t && t.accent)) || CFG.accents[0];
  root.setProperty('--accent', acc.main);
  root.setProperty('--accent-2', acc.a2);
  root.setProperty('--accent-3', acc.a3);
  root.setProperty('--accent-deep', acc.deep);
  root.setProperty('--accent-ink', acc.ink);
  root.setProperty('--accent-glow', acc.main + '73');
  const fset = CFG.fontSets.find((f) => f.name === (t && t.fonts)) || CFG.fontSets[0];
  root.setProperty('--font-display', fset.display);
  root.setProperty('--font-head', fset.head);
  root.setProperty('--font-body', fset.body);
  root.setProperty('--font-mono', fset.mono);
}

function initReveal() {
  const els = document.querySelectorAll('.reveal');
  if (prefersReduced) {els.forEach((e) => e.classList.add('in'));return;}
  const io = new IntersectionObserver((ents) => {
    ents.forEach((e) => {if (e.isIntersecting) {e.target.classList.add('in');io.unobserve(e.target);}});
  }, { threshold: 0.12, rootMargin: '0px 0px -6% 0px' });
  els.forEach((e) => io.observe(e));
}

/* ---------------------------------------------------------------- cross-page persistence */
const LS_KEY = 'presenca.tweaks.v1';
function loadSaved() {
  try {return JSON.parse(localStorage.getItem(LS_KEY)) || {};} catch (e) {return {};}
}
function saveTweaks(obj) {
  try {localStorage.setItem(LS_KEY, JSON.stringify(obj));} catch (e) {}
}

/* ---------------------------------------------------------------- PageShell + mountPage */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#1FB6CE",
  "fonts": "Cinzel / Bebas",
  "aura": true,
  "bgWords": true,
  "first": "LUCAS",
  "last": "BERTONI"
} /*EDITMODE-END*/;

function PageShell({ active, bgWords, children }) {
  // merge any cross-page choices saved from a previous page over the defaults
  const [t, setTweak] = useTweaks(Object.assign({}, TWEAK_DEFAULTS, loadSaved()));

  useEffect(() => {applyTheme(t);}, [t.accent, t.fonts]);
  useEffect(() => {saveTweaks(t);}, [t.accent, t.fonts, t.aura, t.bgWords, t.first, t.last]);
  useEffect(() => {initReveal();}, []);

  return (
    <React.Fragment>
      {t.aura ? <Aura /> : null}
      <Header active={active} />
      <main className="page-container">
        {t.bgWords ? <BackgroundWords words={bgWords} /> : null}
        <div className="page-content">{typeof children === 'function' ? children(t) : children}</div>
      </main>
      <Footer />

      <TweaksPanel>
        <TweakSection label="Marca" />
        <TweakText label="Nome — linha 1" value={t.first} onChange={(v) => setTweak('first', v)} />
        <TweakText label="Nome — linha 2" value={t.last} onChange={(v) => setTweak('last', v)} />
        <TweakSection label="Cor de destaque" />
        <TweakColor label="Acento" value={t.accent}
        options={CFG.accents.map((a) => a.main)}
        onChange={(v) => setTweak('accent', v)} />
        <TweakSection label="Tipografia" />
        <TweakRadio label="Display" value={t.fonts}
        options={CFG.fontSets.map((f) => f.name)}
        onChange={(v) => setTweak('fonts', v)} />
        <TweakSection label="Ambiente" />
        <TweakToggle label="Aura refratada" value={t.aura} onChange={(v) => setTweak('aura', v)} />
        <TweakToggle label="Palavras de fundo" value={t.bgWords} onChange={(v) => setTweak('bgWords', v)} />
      </TweaksPanel>
    </React.Fragment>);

}

// each page calls: mountPage('home', (t) => <HomeContent t={t} />, ['TREINO', ...])
function mountPage(active, render, bgWords) {
  // apply saved theme ASAP to avoid a flash of default accent
  applyTheme(Object.assign({}, TWEAK_DEFAULTS, loadSaved()));
  ReactDOM.createRoot(document.getElementById('root')).
  render(<PageShell active={active} bgWords={bgWords}>{render}</PageShell>);
}

Object.assign(window, {
  CFG, C, NAV, waLink, prefersReduced, isTouch,
  Aura, BackgroundWords, Header, Footer, WhatsAppButton, WhatsAppIcon, CtaBand, QuoteCard, PageHero,
  applyTheme, initReveal, PageShell, mountPage
});