/* ============================================================
   BRITO · NOESIS — page sections (window globals)
   ============================================================ */
const { useState: uState, useEffect: uEffect, useRef: uRef } = React;

/* ---------- Top bar + language toggle ---------- */
function TopBar({ t, lang, setLang }) {
  const [solid, setSolid] = uState(false);
  uEffect(() => {
    const on = () => setSolid(window.scrollY > 80);
    on(); window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  return (
    <header className={"topbar" + (solid ? " solid" : "")}>
      <a className="brand" href="#top" aria-label="NOESIS">
        <PhiMark w={18} />
        <span className="bn">NOESIS<small> · BRITO</small></span>
      </a>
      <div className="lang" role="group" aria-label="Language">
        <button className={lang === 'pt' ? 'on' : ''} onClick={() => setLang('pt')}>PT</button>
        <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
      </div>
    </header>
  );
}

/* ---------- Scroll progress ---------- */
function Progress() {
  const bar = uRef(null);
  uEffect(() => {
    const on = () => {
      const h = document.documentElement;
      const p = h.scrollTop / (h.scrollHeight - h.clientHeight || 1);
      if (bar.current) bar.current.style.width = (p * 100) + '%';
    };
    on(); window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  return <div className="progress" ref={bar}></div>;
}

/* ---------- HERO · NOESIS ---------- */
function Hero({ t }) {
  return (
    <section className="hero" id="top">
      <div className="hero-inner">
        <div className="phi-stage reveal" data-hot>
          <div className="glow"></div>
          <OrbitRings />
          <img className="mark pulse" src="assets/logo-mark.png" alt="The Observer Mark — símbolo do NOESIS" />
        </div>
        <span className="eyebrow reveal d1">{t.hero.eyebrow}</span>
        <h1 className="reveal d1">{t.hero.name}</h1>
        <p className="expansion reveal d2">{t.hero.expansion}</p>
        <p className="mission reveal d2">{t.hero.mission}</p>
        <div className="meta reveal d3">
          {t.hero.chips.map((c, i) => (
            <span className="chip" key={i}><span className="dot"></span>{c}</span>
          ))}
        </div>
      </div>
      <div className="float-cue reveal d4" style={{ position: 'absolute', bottom: 32, left: '50%', transform: 'translateX(-50%)' }}>
        <span></span>{t.hero.cue}
      </div>
    </section>
  );
}

/* ---------- BRITO INTRODUCTION ---------- */
function BritoIntro({ t }) {
  const b = t.intro;
  return (
    <section className="section brito-intro" id="brito">
      <div className="wrap">
        <div className="bi-grid">
          <div className="bi-text">
            <span className="eyebrow reveal">{b.eyebrow}</span>
            <p className="bi-framing reveal d1">{b.framing}</p>
            <h2 className="bi-name reveal d1">{b.name}</h2>
            <p className="bi-tagline reveal d2">{b.tagline}</p>
            <p className="bi-blurb reveal d2">{b.blurb}</p>
            <span className="bi-version mono reveal d3">{b.version}</span>
          </div>
          <div className="bi-portrait reveal d2">
            <div className="bi-glow"></div>
            <img src="assets/brito-cutout.png" alt="BRITO — figura de corpo inteiro, recorte na forma do personagem" />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- MANIFESTO ---------- */
function Manifesto({ t }) {
  const m = t.manifesto;
  return (
    <section className="section manifesto" id="filosofia">
      <div className="wrap-narrow">
        <span className="eyebrow reveal" style={{ display: 'block', textAlign: 'center', marginBottom: 8 }}>{m.eyebrow}</span>
        <div className="quote-mark reveal d1">&ldquo;</div>
        <p className="big reveal d1">
          {m.lead} <em>{m.emph}</em> {m.tail}
        </p>
        <div className="attrib reveal d2" style={{ textAlign: 'center' }}>
          <span className="eyebrow">{m.attrib}</span>
        </div>
      </div>
    </section>
  );
}

/* ---------- THE OBSERVER MARK ---------- */
function ObserverMark({ t }) {
  const m = t.mark;
  return (
    <section className="section" id="simbolo">
      <div className="wrap">
        <SectionHead eyebrow={m.eyebrow} title={m.title} />
        <div className="mark-grid">
          <CornerFrame className="mark-stage reveal">
            <div className="mglow"></div>
            <img src="assets/observer-mark.png" alt="The Observer Mark — símbolo φ com linhas de construção" />
            <div className="mcap"><span className="mono">{m.caption}</span></div>
          </CornerFrame>
          <div className="mark-read reveal d2">
            <div className="mname cinzel">{m.internalName}</div>
            <p className="msub">{m.sub}</p>
            <ol className="readings">
              {m.readings.map((r, i) => (
                <li key={i}>
                  <span className="ri mono">{String(i + 1).padStart(2, '0')}</span>
                  <div>
                    <h3>{r[0]}</h3>
                    <p>{r[1]}</p>
                  </div>
                </li>
              ))}
            </ol>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- IDENTITY ---------- */
function Identity({ t }) {
  const id = t.identity;
  return (
    <section className="section" id="identidade">
      <div className="wrap">
        <SectionHead eyebrow={id.eyebrow} title={id.title} />
        <div className="id-grid">
          <CornerFrame className="panel spec reveal">
            <dl>
              {id.rows.map((r, i) => (
                <div className="row" key={i}>
                  <dt>{r[0]}</dt>
                  <dd>{r[2] ? <strong>{r[1]}</strong> : r[1]}</dd>
                </div>
              ))}
            </dl>
          </CornerFrame>
          <CornerFrame className="portrait-card reveal d2">
            <img src="assets/portrait.png" alt="Retrato de BRITO" loading="lazy" />
            <div className="cap"><span>{id.portraitCap[0]}</span><span className="mono">{id.portraitCap[1]}</span></div>
          </CornerFrame>
        </div>
      </div>
    </section>
  );
}

/* ---------- PIPELINE ---------- */
const PIPE_GLYPHS = ["learning", "memory", "experiment", "synthesis", "reasoning", "evolution"];
function Pipeline({ t }) {
  const p = t.pipeline;
  return (
    <section className="section" id="funcao">
      <div className="wrap">
        <SectionHead eyebrow={p.eyebrow} title={p.title} />
        <p className="reveal" style={{ color: 'var(--muted)', maxWidth: '54ch', marginTop: -28, marginBottom: 44, fontSize: 'clamp(15px,1.5vw,18px)' }}>{p.intro}</p>
        <CornerFrame className="panel reveal d1">
          <div className="pipe">
            {p.nodes.map((n, i) => (
              <div className="node" key={i}>
                <span className="mono" style={{ fontSize: 10, color: 'var(--gold-deep)', letterSpacing: '0.12em' }}>{String(i + 1).padStart(2, '0')}</span>
                <div className="glyph"><Glyph name={PIPE_GLYPHS[i]} /></div>
                <span className="nm">{n[0]}</span>
                <span className="ds">{n[1]}</span>
              </div>
            ))}
          </div>
          <div className="sig-row">
            <PhiMark w={34} />
            <div>
              <div className="t1">{p.sig.t1}</div>
              <div className="t2">{p.sig.t2}</div>
            </div>
          </div>
        </CornerFrame>
      </div>
    </section>
  );
}

/* ---------- PRINCIPLES ---------- */
const PRINC_GLYPHS = ["eye", "experiment", "synthesis", "adapt", "evolution"];
function Principles({ t }) {
  const pr = t.principles;
  return (
    <section className="section" id="principios">
      <div className="wrap">
        <SectionHead eyebrow={pr.eyebrow} title={pr.title} />
        <div className="princ reveal d1">
          {pr.cards.map((c, i) => (
            <div className="pcard" key={i}>
              <span className="idx">{String(i + 1).padStart(2, '0')}</span>
              <div className="glyph"><Glyph name={PRINC_GLYPHS[i]} /></div>
              <h3>{c[0]}</h3>
              <p className="ax"><b>{c[1]}</b> {c[2]}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- VISTAS — interactive 3D viewer + site-side control panel ---------- */
function Gallery({ t }) {
  const g = t.gallery;
  const frameRef = uRef(null);
  const [rotating, setRotating] = uState(true);
  const [active, setActive] = uState('');
  const api = () => { try { return frameRef.current && frameRef.current.contentWindow && frameRef.current.contentWindow.britoEmbed; } catch (e) { return null; } };
  // the embedded model is heavy (~15s). If the API isn't ready yet, retry until it is,
  // so a click made during loading still applies once the viewer is live.
  const callApi = (fn) => {
    let tries = 0;
    const attempt = () => {
      const a = api();
      if (a) { try { fn(a); } catch (e) {} return; }
      if (tries++ < 80) setTimeout(attempt, 350);
    };
    attempt();
  };
  const view = (k) => { callApi(a => a.view(k)); setActive(k); setRotating(false); };
  const focus = (k) => { callApi(a => a.focus(k)); setActive(k); setRotating(false); };
  const toggle = () => { callApi(a => setRotating(a.toggleRotate())); };
  const views = [['front', 'Frente'], ['right', 'Lateral D'], ['left', 'Lateral E'], ['back', 'Costas']];
  const parts = [['eye', 'Olho'], ['plaque', 'Plaqueta'], ['base', 'Base'], ['home', 'Geral']];
  return (
    <section className="section" id="vistas">
      <div className="wrap">
        <SectionHead eyebrow={g.eyebrow} title={g.title} />
        <p className="reveal" style={{ color: 'var(--muted)', maxWidth: '60ch', marginTop: -28, marginBottom: 44, fontSize: 'clamp(15px,1.5vw,18px)' }}>{g.intro}</p>
        <div className="v3d reveal d1">
          <aside className="v3d-controls">
            <div className="v3d-grp">
              <span className="v3d-lbl">Rotação</span>
              <button className={"v3d-btn" + (!rotating ? " on" : "")} onClick={toggle}>{rotating ? '❚❚  Pausar' : '▶  Girar'}</button>
            </div>
            <div className="v3d-grp">
              <span className="v3d-lbl">Vistas</span>
              {views.map(([k, l]) => <button key={k} className={"v3d-btn" + (active === k ? " on" : "")} onClick={() => view(k)}>{l}</button>)}
            </div>
            <div className="v3d-grp">
              <span className="v3d-lbl">Foco</span>
              {parts.map(([k, l]) => <button key={k} className={"v3d-btn" + (active === k ? " on" : "")} onClick={() => focus(k)}>{l}</button>)}
            </div>
          </aside>
          <div className="v3d-stage">
            <iframe
              ref={frameRef}
              src="viewer-3d.html?embed=1&v=8"
              title="BRITO — visualizador 3D interativo"
              loading="lazy"
              allowFullScreen
            ></iframe>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- CLOSING line ---------- */
function Closing({ t }) {
  return (
    <section className="section" style={{ textAlign: 'center' }}>
      <div className="wrap-narrow">
        <PhiMark className="reveal" w={30} />
        <h2 className="reveal d1" style={{ fontSize: 'clamp(30px,6vw,72px)', lineHeight: 1.12, marginTop: 26, letterSpacing: '0.03em' }}>
          <span style={{ color: 'var(--muted)' }}>{t.closing.a}</span><br />
          <span style={{ color: 'var(--ivory)' }}>{t.closing.b}</span>
        </h2>
      </div>
    </section>
  );
}

/* ---------- DECLARATION ---------- */
function Declaration({ t }) {
  const d = t.declaration;
  const [open, setOpen] = uState(false);
  uEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  const src = t.code === 'PT' ? "assets/declaration-pt.png" : "assets/declaration-en.png";
  return (
    <section className="section decl" id="declaracao">
      <div className="wrap">
        <SectionHead eyebrow={d.eyebrow} title={d.title} />
        <div className="reveal d1" style={{ display: 'grid', placeItems: 'center' }}>
          <div className="parch-img frame" onClick={() => setOpen(true)} data-hot>
            <span className="c tl"></span><span className="c tr"></span>
            <span className="c bl"></span><span className="c br"></span>
            <img src={src} alt={d.title + " — NOESIS · BRITO"} />
          </div>
        </div>
      </div>
      <div className={"lightbox" + (open ? " open" : "")} onClick={() => setOpen(false)}>
        {open && <img src={src} alt="" onClick={(e) => e.stopPropagation()} />}
        <button className="x" onClick={() => setOpen(false)}>ESC ✕</button>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer({ t }) {
  const f = t.foot;
  return (
    <footer className="foot" id="rodape">
      <div className="wrap">
        <div className="fmark reveal"><PhiMark w={34} /></div>
        <div className="fname reveal d1">{f.name}</div>
        <div className="fsub reveal d1">{f.sub}</div>
        <div className="flatin reveal d2">&ldquo;{f.latin}&rdquo;</div>
        <div className="fmeta reveal d2">
          {f.meta.map((m, i) => <span key={i}>{m}</span>)}
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { TopBar, Progress, Hero, BritoIntro, Manifesto, ObserverMark, Identity, Pipeline, Principles, Gallery, Closing, Declaration, Footer });
