/**
 * Cinematic.jsx — animações da v5 (versão saneada após bugs de pin/reveal).
 *
 * Stack: GSAP + ScrollTrigger + Lenis (CDN, ver index.html).
 *
 * Decisões pós-bug:
 *  - SEM pin scroll: o pin + scrub estava deixando elementos travados em
 *    estados intermediários (opacity ~0.18) quando o trigger não completava.
 *  - SEM reveal global que aplica opacity:0 em toda seção: quando o trigger
 *    falhava em recalcular (Lenis + Babel async + ScrollTrigger), seções
 *    inteiras ficavam invisíveis ("buraco em branco" entre seções).
 *  - Mantido: smooth scroll (Lenis), timeline do hero (reveal das linhas) e
 *    fade controlado do indicador de scroll.
 *  - Safety net: depois de 2.5s força opacity:1 / transform:none em qualquer
 *    elemento que tenha ficado preso em estado oculto.
 */
(function () {
  const EASE = 'power3.out';
  const DUR  = 1.0;

  function ready() {
    if (!window.gsap || !window.ScrollTrigger || !window.Lenis) return false;
    const root = document.getElementById('root');
    return root && root.firstChild && document.querySelector('.hero');
  }

  function safetyNet() {
    // Failsafe: garante que NADA fique permanentemente invisível por causa
    // de um trigger que não disparou. Roda 2.5s após init.
    setTimeout(() => {
      document.querySelectorAll(
        '.hero-copy, .hero-vsl-wrap, .hero-chat, .hero-vsl-cta, .hero-trust-micro, .section, .trust-bar, .cta-final, .footer'
      ).forEach((el) => {
        // só limpa o que está visivelmente oculto
        const cs = getComputedStyle(el);
        if (parseFloat(cs.opacity) < 0.95) el.style.opacity = '1';
      });
    }, 2500);
  }

  function init() {
    if (!ready()) return setTimeout(init, 60);

    const { gsap, ScrollTrigger, Lenis } = window;
    gsap.registerPlugin(ScrollTrigger);

    // ===== Lenis (smooth scroll) =====
    const lenis = new Lenis({
      duration: 1.25,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      smoothTouch: false,
      touchMultiplier: 1.2,
      lerp: 0.10,
    });
    function raf(time) { lenis.raf(time); requestAnimationFrame(raf); }
    requestAnimationFrame(raf);
    lenis.on('scroll', ScrollTrigger.update);
    gsap.ticker.add((time) => lenis.raf(time * 1000));
    gsap.ticker.lagSmoothing(0);

    // ===== HERO — reveal cinematográfico (timeline única, sem depender de scroll) =====
    const heroTl = gsap.timeline({ defaults: { ease: EASE, duration: DUR } });
    heroTl
      .from('.hero-copy h1 .line', { y: 70, opacity: 0, stagger: 0.20, duration: 1.05 }, 0.25)
      .from('.hero-sub',           { y: 26, opacity: 0, duration: 0.9 }, '-=0.55')
      .from('.hero-vsl-intro',     { y: 16, opacity: 0, duration: 0.85 }, '-=0.6')
      .from('.hero-chat',          { y: 50, opacity: 0, duration: 1.15 }, '-=0.7')
      .from('.hero-vsl-cta',       { y: 16, opacity: 0, duration: 0.8 }, '-=0.55')
      .from('.hero-trust-micro',   { y: 12, opacity: 0, duration: 0.75 }, '-=0.55')
      .from('.hero-scroll-ind',    { y: -10, opacity: 0, duration: 0.85 }, '-=0.4');

    // Indicador de scroll some conforme desce (scrub) — único uso de scrub.
    gsap.to('.hero-scroll-ind', {
      opacity: 0,
      y: 18,
      ease: EASE,
      scrollTrigger: {
        start: 'top top',
        end: '+=260',
        scrub: 0.6,
      },
    });

    // ===== Links âncora — scroll suave via Lenis =====
    document.addEventListener('click', (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute('href');
      if (!href || href === '#' || href.length < 2) return;
      const target = document.querySelector(href);
      if (!target) return;
      e.preventDefault();
      lenis.scrollTo(target, {
        offset: -20,
        duration: 1.4,
        easing: (t) => 1 - Math.pow(1 - t, 3),
      });
    });

    // Recálculos pós-load / fonts (Lenis pode mudar alturas).
    const refresh = () => ScrollTrigger.refresh();
    window.addEventListener('load', refresh);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(refresh);

    safetyNet();
    document.documentElement.classList.add('cinematic-ready');
    window.__cinematic = { gsap, ScrollTrigger, lenis };
  }

  init();
})();
