// -------------------------------------------------------------------------
// SCROLL PROGRESS — barra de progresso de leitura
//
// Destino: /lp/components/hero.jsx — renderize <BarraProgresso /> uma vez,
//          dentro de Nav (ou logo no topo de App, em app.jsx).
// Protótipo: lab/protos/scroll-progress.html · Ficha: refs/scroll-progress/ficha.md
// PORTE MANUAL: o protótipo é CSS + JS puro, sem bloco babel, então este arquivo
// não sai de tools/portar.py. Mudou o protótipo? Ajuste aqui também.
// -------------------------------------------------------------------------

(function () {
  function BarraProgresso() {
    const ref = React.useRef(null);

    React.useEffect(() => {
      const barra = ref.current;
      if (!barra) return;
      // Com animation-timeline o browser resolve tudo no compositor: nem
      // listener nem JS por frame. Só instalamos o fallback se não houver.
      if (CSS.supports('animation-timeline', 'scroll()')) return;

      let pendente = false;
      const atualiza = () => {
        const d = document.documentElement;
        const p = d.scrollTop / Math.max(1, d.scrollHeight - d.clientHeight);
        barra.style.transform = 'scaleX(' + Math.min(1, Math.max(0, p)) + ')';
        pendente = false;
      };
      // rAF + passive: no máximo uma medição por frame, nunca bloqueia o scroll.
      const onScroll = () => {
        if (!pendente) { pendente = true; requestAnimationFrame(atualiza); }
      };
      addEventListener('scroll', onScroll, { passive: true });
      addEventListener('resize', atualiza, { passive: true });
      atualiza();
      return () => {
        removeEventListener('scroll', onScroll);
        removeEventListener('resize', atualiza);
      };
    }, []);

    return (
      <React.Fragment>
        <style>{`
          #cartroi-barra-progresso {
            position: fixed; inset: 0 0 auto 0; height: 3px; z-index: 60;
            transform-origin: 0 50%; transform: scaleX(0);
            background: linear-gradient(90deg, #7c3aed, #a78bfa 55%, #22d3ee);
            will-change: transform;
          }
          @supports (animation-timeline: scroll()) {
            #cartroi-barra-progresso {
              animation: cartroi-encher linear both;
              animation-timeline: scroll(root block);
            }
            @keyframes cartroi-encher { from { transform: scaleX(0) } to { transform: scaleX(1) } }
          }
          /* Decorativa: sem ela não se perde informação. */
          @media (prefers-reduced-motion: reduce) { #cartroi-barra-progresso { display: none } }
        `}</style>
        <div id="cartroi-barra-progresso" ref={ref} aria-hidden="true"></div>
      </React.Fragment>
    );
  }

  Object.assign(window, { BarraProgresso });
})();
