/* ═══════════════════════════════════════════════════════════════
   ARANTES TECNOLOGIA — main.js v2.0
   GSAP 3 + ScrollTrigger + Three.js + Lenis + VanillaTilt
   ═══════════════════════════════════════════════════════════════ */

// ──────────────────────────────────────────────────────────────
// REGISTRO DE PLUGINS GSAP
// ──────────────────────────────────────────────────────────────
gsap.registerPlugin(ScrollTrigger);

// ──────────────────────────────────────────────────────────────
// LENIS — SMOOTH SCROLL
// ──────────────────────────────────────────────────────────────
let lenis;

function initLenis() {
  lenis = new Lenis({
    duration: 1.4,
    easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
    direction: 'vertical',
    smooth: true,
  });

  lenis.on('scroll', ScrollTrigger.update);
  gsap.ticker.add((time) => lenis.raf(time * 1000));
  gsap.ticker.lagSmoothing(0);
}

// ──────────────────────────────────────────────────────────────
// LOADER
// ──────────────────────────────────────────────────────────────
function initLoader() {
  const loader = document.getElementById('loader');
  if (!loader) return;

  document.body.style.overflow = 'hidden';

  const obj = { value: 0 };
  const tl = gsap.timeline({
    onComplete: () => {
      loader.style.pointerEvents = 'none';
      document.body.style.overflow = '';
    }
  });

  tl.to(obj, {
    value: 100,
    duration: 1.8,
    ease: 'power2.inOut',
    onUpdate() {
      const count = document.querySelector('.loader-count');
      if (count) count.textContent = Math.round(obj.value) + '%';
    }
  })
  .to('.loader-bar-fill', { scaleX: 1, duration: 1.8, ease: 'power2.inOut' }, 0)
  .to(loader, { yPercent: -100, duration: 0.75, ease: 'power4.inOut' }, '+=0.15');
}



// ──────────────────────────────────────────────────────────────
// NAVBAR
// ──────────────────────────────────────────────────────────────
function initNavScroll() {
  const nav = document.querySelector('nav');
  if (!nav) return;

  ScrollTrigger.create({
    onUpdate(self) {
      if (self.direction === -1) {
        gsap.to(nav, { y: 0, duration: 0.4, ease: 'power2.out' });
      } else if (window.scrollY > 120) {
        gsap.to(nav, { y: -150, duration: 0.3, ease: 'power2.in' });
      }
    }
  });

  ScrollTrigger.create({
    start: 80,
    onEnter:     () => nav.classList.add('scrolled'),
    onLeaveBack: () => nav.classList.remove('scrolled'),
  });


}

// ──────────────────────────────────────────────────────────────
// HERO — Splitting.js char animation
// ──────────────────────────────────────────────────────────────
function initHero() {
  // Splitting.js for char split
  if (typeof Splitting !== 'undefined') {
    Splitting();
  }

  // Variable Proximity Effect — guardar instância para poder pausar/retomar
  let vpInstance = null;
  if (window.VariableProximity) {
    vpInstance = new VariableProximity('.hero-title', {
      radius: 70,
      falloff: 'exponential',
      fromSettings: { wght: 400, opsz: 14 },
      toSettings: { wght: 1000, opsz: 48 }
    });
  }

  // IntersectionObserver: pausa VariableProximity + scroll-indicator
  // quando a Hero sai completamente da viewport
  const heroSection    = document.getElementById('hero');
  const scrollDot      = document.querySelector('.scroll-indicator-dot');

  if (heroSection) {
    const heroIO = new IntersectionObserver(
      ([entry]) => {
        const visible = entry.isIntersecting;

        // VariableProximity: para listener de mousemove + rAF processing
        if (vpInstance) {
          visible ? vpInstance.resume() : vpInstance.pause();
        }

        // Scroll indicator: pausa CSS animation infinita quando invisível
        if (scrollDot) {
          scrollDot.style.animationPlayState = visible ? 'running' : 'paused';
        }
      },
      {
        // threshold 0 = dispara assim que qualquer pixel entra/sai
        threshold: 0,
        rootMargin: '0px'
      }
    );
    heroIO.observe(heroSection);
  }

  const tl = gsap.timeline({ delay: 2.2 }); // Após loader

  tl
    .from('.hero-tag', {
      y: -30, opacity: 0, duration: 0.6, ease: 'power3.out'
    })
    .from('[data-splitting] .char', {
      y: 100,
      opacity: 0,
      rotateX: -90,
      transformOrigin: '50% 100%',
      stagger: { amount: 0.6, ease: 'power2.out' },
      duration: 0.8,
      ease: 'back.out(1.4)',
    }, '-=0.2')
    .from('.hero-subtitle', {
      y: 30, opacity: 0, duration: 0.7, ease: 'power2.out'
    }, '-=0.4')
    .from('.hero-buttons > *', {
      y: 20, opacity: 0, scale: 0.9,
      stagger: 0.15, duration: 0.6, ease: 'back.out(2)',
    }, '-=0.3')
    .from('.scroll-indicator', {
      opacity: 0, duration: 0.5
    }, '-=0.2');
}




// Função initLogo3D removida a pedido do usuário (troca por imagem estática)

// ──────────────────────────────────────────────────────────────
// MARQUEE
// ──────────────────────────────────────────────────────────────
function initMarquee() {
  document.querySelectorAll('.marquee-track').forEach(track => {
    track.innerHTML += track.innerHTML;
    const totalWidth = track.scrollWidth / 2;

    const anim = gsap.to(track, {
      x: -totalWidth,
      duration: 28,
      ease: 'none',
      repeat: -1,
    });

    track.addEventListener('mouseenter', () => gsap.to(anim, { timeScale: 0.3, duration: 0.5 }));
    track.addEventListener('mouseleave', () => gsap.to(anim, { timeScale: 1.0, duration: 0.5 }));

    // Pausar quando fora da viewport (economiza CPU/GPU)
    const io = new IntersectionObserver(
      ([entry]) => entry.isIntersecting ? anim.play() : anim.pause(),
      { rootMargin: '120px 0px' }
    );
    io.observe(track.parentElement || track);
  });
}

// ──────────────────────────────────────────────────────────────
// LOGO TICKER
// ──────────────────────────────────────────────────────────────
function initLogoTicker() {
  const track = document.querySelector('.logo-ticker');
  if (!track) return;
  track.innerHTML += track.innerHTML;
  const w = track.scrollWidth / 2;
  const anim = gsap.to(track, { x: -w, duration: 20, ease: 'none', repeat: -1 });

  // Pausar quando fora da viewport
  const io = new IntersectionObserver(
    ([entry]) => entry.isIntersecting ? anim.play() : anim.pause(),
    { rootMargin: '120px 0px' }
  );
  io.observe(track.parentElement || track);
}

// ──────────────────────────────────────────────────────────────
// CARDS — stagger entry com ScrollTrigger
// ──────────────────────────────────────────────────────────────
function initCards() {
  // Service cards
  gsap.from('.service-card', {
    scrollTrigger: {
      trigger: '.services-grid',
      start: 'top 88%',
      toggleActions: 'play none none none',
    },
    y: 60,
    opacity: 0,
    duration: 0.7,
    stagger: 0.07,
    ease: 'power3.out',
  });

  // Testimonial cards
  gsap.from('.testimonial-card', {
    scrollTrigger: {
      trigger: '.testimonials-grid',
      start: 'top 85%',
      toggleActions: 'play none none none',
    },
    y: 50,
    opacity: 0,
    rotateY: 8,
    duration: 0.8,
    stagger: 0.1,
    ease: 'power3.out',
  });

  // Section headers — fade up
  gsap.utils.toArray('[data-gsap="fade-up"]').forEach(el => {
    gsap.from(el, {
      scrollTrigger: { trigger: el, start: 'top 85%' },
      y: 40,
      opacity: 0,
      duration: 0.7,
      ease: 'power3.out',
    });
  });

  // Split sections — left/right slide
  gsap.utils.toArray('[data-gsap="slide-left"]').forEach(el => {
    gsap.from(el, {
      scrollTrigger: { trigger: el, start: 'top 80%' },
      x: -60,
      opacity: 0,
      duration: 0.9,
      ease: 'power3.out',
    });
  });

  gsap.utils.toArray('[data-gsap="slide-right"]').forEach(el => {
    gsap.from(el, {
      scrollTrigger: { trigger: el, start: 'top 80%' },
      x: 60,
      opacity: 0,
      duration: 0.9,
      ease: 'power3.out',
    });
  });

  // Scale up (newsletter, CTA)
  gsap.utils.toArray('[data-gsap="scale-up"]').forEach(el => {
    gsap.from(el, {
      scrollTrigger: { trigger: el, start: 'top 80%' },
      scale: 0.88,
      opacity: 0,
      duration: 0.9,
      ease: 'power3.out',
    });
  });

  // Footer cols stagger
  gsap.utils.toArray('.footer-col').forEach((col, i) => {
    gsap.from(col, {
      scrollTrigger: { trigger: col, start: 'top 90%' },
      y: 30,
      opacity: 0,
      duration: 0.6,
      delay: i * 0.1,
      ease: 'power2.out',
    });
  });
}

// ──────────────────────────────────────────────────────────────
// COUNTERS — Slot Machine / Odometer Effect
// ──────────────────────────────────────────────────────────────
function initCounters() {
  const counters = [
    { selector: '[data-count="sistemas"]',    end: 500, decimals: 0 },
    { selector: '[data-count="processados"]', end: 2.5, decimals: 1 },
  ];

  counters.forEach(({ selector, end, decimals }) => {
    const el = document.querySelector(selector);
    if (!el) return;
    
    // Clear initial text
    el.innerHTML = '';
    const strValue = end.toFixed(decimals);
    
    const container = document.createElement('span');
    container.className = 'counter-container';
    
    const counterCounter = document.createElement('span');
    counterCounter.className = 'counter-counter';
    container.appendChild(counterCounter);
    
    // Add gradient overlays
    const gradientContainer = document.createElement('span');
    gradientContainer.className = 'gradient-container';
    gradientContainer.innerHTML = '<span class="top-gradient"></span><span class="bottom-gradient"></span>';
    container.appendChild(gradientContainer);
    
    el.appendChild(container);
    
    const strips = [];
    
    for (let i = 0; i < strValue.length; i++) {
        const char = strValue[i];
        
        const digitContainer = document.createElement('span');
        digitContainer.className = 'counter-digit';
        
        if (char === '.' || char === ',') {
            digitContainer.innerHTML = `<span class="counter-number">${char}</span>`;
            digitContainer.style.width = 'fit-content';
            counterCounter.appendChild(digitContainer);
        } else {
            const num = parseInt(char, 10);
            const strip = document.createElement('span');
            strip.className = 'counter-strip';
            
            let stripContent = '';
            // Create the spinning strip.
            // 2 full sets of 0-9 then the target digit.
            for (let j = 0; j < 20; j++) {
                stripContent += `<span class="counter-number">${j % 10}</span>`;
            }
            stripContent += `<span class="counter-number">${num}</span>`;
            
            strip.innerHTML = stripContent;
            digitContainer.appendChild(strip);
            counterCounter.appendChild(digitContainer);
            
            strips.push(strip);
        }
    }
    
    // Animate the strips on scroll
    ScrollTrigger.create({
        trigger: el,
        start: 'top 85%',
        once: true,
        onEnter: () => {
            strips.forEach((strip, i) => {
                // translate by exactly 20 parent heights, perfectly resting on the final number
                gsap.fromTo(strip, 
                    { y: '0em' }, 
                    { 
                      y: '-22em',
                      duration: 1.8 + i * 0.4,
                      ease: 'power3.inOut' 
                    }
                );
            });
        }
    });
  });
}

// ──────────────────────────────────────────────────────────────
// PARALLAX nas imagens
// ──────────────────────────────────────────────────────────────
function initParallax() {
  gsap.utils.toArray('.parallax-img').forEach(img => {
    const depth = parseFloat(img.dataset.depth) || 0.3;
    gsap.to(img, {
      yPercent: -30 * depth,
      ease: 'none',
      scrollTrigger: {
        trigger: img.closest('section') || img,
        start: 'top bottom',
        end: 'bottom top',
        scrub: true,
      },
    });
  });
}

// ──────────────────────────────────────────────────────────────
// ANIMATED DOCK
// ──────────────────────────────────────────────────────────────
function initDock() {
  const dockPanel = document.querySelector('.footer-socials');
  const dockItems = document.querySelectorAll('.footer-socials .dock-item');
  if (!dockPanel || dockItems.length === 0) return;

  const baseItemSize = 42;
  const magnification = 60;
  const distance = 150;

  // Use GSAP quickTo to smoothly update sizes
  const itemAnimatorsW = Array.from(dockItems).map(item => gsap.quickTo(item, "width", { duration: 0.25, ease: "power2.out" }));
  const itemAnimatorsH = Array.from(dockItems).map(item => gsap.quickTo(item, "height", { duration: 0.25, ease: "power2.out" }));

  dockPanel.addEventListener('mousemove', (e) => {
    let hoveredAny = false;
    
    dockItems.forEach((item, index) => {
      const rect = item.getBoundingClientRect();
      const itemCenterX = rect.left + rect.width / 2;
      const mouseDistance = Math.abs(e.clientX - itemCenterX);

      if (mouseDistance < distance) {
        // Linear scale
        const progress = 1 - (mouseDistance / distance);
        const targetSize = baseItemSize + (magnification - baseItemSize) * progress;
        itemAnimatorsW[index](targetSize);
        itemAnimatorsH[index](targetSize);
        hoveredAny = true;
      } else {
        itemAnimatorsW[index](baseItemSize);
        itemAnimatorsH[index](baseItemSize);
      }
    });

    if (hoveredAny) {
      // no panel to resize
    } else {
      // no panel to resize
    }
  });

  dockPanel.addEventListener('mouseleave', () => {
    dockItems.forEach((item, index) => {
      itemAnimatorsW[index](baseItemSize);
      itemAnimatorsH[index](baseItemSize);
      item.classList.remove('hovered');
    });
  });

  dockItems.forEach((item) => {
    item.addEventListener('mouseenter', () => item.classList.add('hovered'));
    item.addEventListener('mouseleave', () => item.classList.remove('hovered'));
    item.addEventListener('focus', () => item.classList.add('hovered'));
    item.addEventListener('blur', () => item.classList.remove('hovered'));
  });
}

// ──────────────────────────────────────────────────────────────
// STEPS — linha scaleX + números bounce
// ──────────────────────────────────────────────────────────────
function initSteps() {
  gsap.to('.steps-connector-fill', {
    scaleX: 1,
    ease: 'none',
    scrollTrigger: {
      trigger: '.steps-wrapper',
      start: 'top 72%',
      end:   'bottom 60%',
      scrub: 1,
    },
  });

  gsap.utils.toArray('.step-number').forEach((num, i) => {
    gsap.from(num, {
      scale: 0,
      opacity: 0,
      duration: 0.6,
      ease: 'back.out(2)',
      scrollTrigger: { trigger: num, start: 'top 82%', once: true },
      delay: i * 0.15,
    });
  });

  gsap.utils.toArray('.step-card').forEach((card, i) => {
    gsap.from(card, {
      y: 30,
      opacity: 0,
      duration: 0.6,
      ease: 'power2.out',
      scrollTrigger: { trigger: card, start: 'top 82%', once: true },
      delay: i * 0.15,
    });
  });
}

// Função initTilt removida para otimização de performance

// ──────────────────────────────────────────────────────────────
// GLASS SPOTLIGHT — luz segue o cursor
// ──────────────────────────────────────────────────────────────
function initGlassSpotlight() {
  document.querySelectorAll('.glass-spotlight').forEach(card => {
    card.addEventListener('mousemove', e => {
      const rect = card.getBoundingClientRect();
      const x = ((e.clientX - rect.left) / rect.width  * 100).toFixed(1) + '%';
      const y = ((e.clientY - rect.top)  / rect.height * 100).toFixed(1) + '%';
      card.style.setProperty('--mx', x);
      card.style.setProperty('--my', y);
    });
    card.addEventListener('mouseleave', () => {
      card.style.setProperty('--mx', '50%');
      card.style.setProperty('--my', '50%');
    });
  });
}

// ──────────────────────────────────────────────────────────────
// MAGNETIC BUTTONS
// ──────────────────────────────────────────────────────────────
function initMagneticButtons() {
  if (window.matchMedia('(hover: none)').matches) return;

  document.querySelectorAll('.btn-magnetic').forEach(btn => {
    const strength = 22;
    btn.addEventListener('mousemove', e => {
      const rect = btn.getBoundingClientRect();
      const cx   = rect.left + rect.width  / 2;
      const cy   = rect.top  + rect.height / 2;
      const dx   = (e.clientX - cx) / (rect.width  / 2);
      const dy   = (e.clientY - cy) / (rect.height / 2);
      gsap.to(btn, {
        x: dx * strength,
        y: dy * strength,
        duration: 0.4,
        ease: 'power2.out',
      });
    });
    btn.addEventListener('mouseleave', () => {
      gsap.to(btn, { x: 0, y: 0, duration: 0.6, ease: 'elastic.out(1, 0.4)' });
    });
  });
}

// ──────────────────────────────────────────────────────────────
// INSTAGRAM PRICING — flip 3D entre abas
// ──────────────────────────────────────────────────────────────
function initPricingTabs() {
  window.flipTab = function(tab) {
    const panels  = document.querySelectorAll('.pricing-table');
    const current = [...panels].find(p => p.style.display !== 'none');
    const next    = document.getElementById('panel-' + tab);
    if (!next || current === next) return;

    // Update tab buttons
    document.querySelectorAll('.pricing-tabs button').forEach(btn => {
      btn.classList.toggle('gs-purple', btn.dataset.tab === tab);
    });

    const tl = gsap.timeline();
    tl.to(current, {
      rotateY: 90, opacity: 0, duration: 0.35, ease: 'power2.in',
      onComplete: () => { current.style.display = 'none'; next.style.display = 'block'; }
    })
    .from(next, { rotateY: -90, opacity: 0, duration: 0.35, ease: 'power2.out' });
  };
}

// ──────────────────────────────────────────────────────────────
// FAQ — GSAP accordion
// ──────────────────────────────────────────────────────────────
function initFAQ() {
  document.querySelectorAll('.faq-trigger').forEach(trigger => {
    trigger.addEventListener('click', () => {
      const item    = trigger.closest('.faq-item');
      const body    = item.querySelector('.faq-body');
      const chevron = item.querySelector('.faq-chevron');
      const isOpen  = item.classList.contains('open');

      // Fechar todos
      document.querySelectorAll('.faq-item.open').forEach(open => {
        open.classList.remove('open');
        gsap.to(open.querySelector('.faq-body'),    { maxHeight: 0,   duration: 0.35, ease: 'power2.inOut' });
        gsap.to(open.querySelector('.faq-chevron'), { rotation: 0,    duration: 0.3 });
      });

      // Abrir o clicado
      if (!isOpen) {
        item.classList.add('open');
        gsap.to(body,    { maxHeight: 400, duration: 0.4, ease: 'power2.inOut' });
        gsap.to(chevron, { rotation: 90,   duration: 0.3 });
      }
    });
  });
}

// ──────────────────────────────────────────────────────────────
// VIDEO MODAL
// ──────────────────────────────────────────────────────────────
function initVideoModal() {
  window.openVideo = function() {
    const overlay = document.getElementById('video-overlay');
    if (overlay) overlay.classList.add('open');
  };

  const closeBtn = document.getElementById('video-close');
  if (closeBtn) {
    closeBtn.addEventListener('click', () => {
      document.getElementById('video-overlay')?.classList.remove('open');
    });
  }

  document.getElementById('video-overlay')?.addEventListener('click', e => {
    if (e.target === e.currentTarget) {
      e.currentTarget.classList.remove('open');
    }
  });
}

// ──────────────────────────────────────────────────────────────
// FLOAT-IMG — Pausa animações CSS quando fora da viewport
// ──────────────────────────────────────────────────────────────
function initFloatPause() {
  const floatImgs = document.querySelectorAll('.float-img');
  if (!floatImgs.length) return;

  const io = new IntersectionObserver(
    (entries) => {
      entries.forEach(entry => {
        entry.target.style.animationPlayState =
          entry.isIntersecting ? 'running' : 'paused';
        // Reduz will-change quando invisível para liberar memória de GPU
        entry.target.style.willChange =
          entry.isIntersecting ? 'transform' : 'auto';
      });
    },
    { rootMargin: '150px 0px' }
  );

  floatImgs.forEach(img => io.observe(img));
}

// ──────────────────────────────────────────────────────────────
// BORDER SPIN — Pausa animação do CTA Final quando fora da viewport
// ──────────────────────────────────────────────────────────────
function initBorderSpinPause() {
  const ctaEl = document.querySelector('.glass-intense');
  if (!ctaEl) return;

  const io = new IntersectionObserver(
    ([entry]) => {
      // Controla a animação borderSpin do ::before via classe
      ctaEl.classList.toggle('border-spin-paused', !entry.isIntersecting);
    },
    { rootMargin: '100px 0px' }
  );
  io.observe(ctaEl);
}

// ──────────────────────────────────────────────────────────────
// NEWSLETTER — Feedback visual após submit
// ──────────────────────────────────────────────────────────────
function initNewsletterFeedback() {
  const forms = [
    { formSel: '.newsletter-form',  btnSel: '#newsletter-btn',      inputSel: '#newsletter-email' },
    { formSel: '.footer-newsletter', btnSel: '#footer-subscribe-btn', inputSel: '#footer-email' },
  ];

  forms.forEach(({ formSel, btnSel, inputSel }) => {
    const form  = document.querySelector(formSel);
    const btn   = document.querySelector(btnSel);
    const input = document.querySelector(inputSel);
    if (!form || !btn || !input) return;

    form.addEventListener('submit', (e) => {
      e.preventDefault();

      // Valida e-mail simples
      if (!input.value || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value)) {
        gsap.fromTo(input,
          { x: 0 },
          { x: 8, duration: 0.08, repeat: 5, yoyo: true, ease: 'power1.inOut',
            onComplete: () => gsap.set(input, { x: 0 }) }
        );
        input.focus();
        return;
      }

      // Feedback de sucesso
      const originalText = btn.textContent.trim();
      const originalBg   = btn.style.background;

      gsap.to(btn, {
        scale: 0.92, duration: 0.12, ease: 'power2.in',
        onComplete: () => {
          btn.textContent = '✓ Inscrito!';
          btn.style.background = 'var(--gradient-success, linear-gradient(135deg,#10B981,#059669))';
          btn.disabled = true;
          input.value = '';
          gsap.to(btn, { scale: 1, duration: 0.3, ease: 'back.out(2)' });

          // Restaurar após 3.5s
          setTimeout(() => {
            btn.textContent = originalText;
            btn.style.background = originalBg;
            btn.disabled = false;
          }, 3500);
        }
      });
    });
  });
}

// ──────────────────────────────────────────────────────────────
// SMOOTH ANCHOR SCROLL
// ──────────────────────────────────────────────────────────────
function initSmoothAnchors() {
  document.querySelectorAll('a[href^="#"]').forEach(link => {
    link.addEventListener('click', e => {
      e.preventDefault();
      const target = document.querySelector(link.getAttribute('href'));
      if (target && lenis) {
        lenis.scrollTo(target, { offset: -80, duration: 1.2 });
      }
    });
  });
}

// ──────────────────────────────────────────────────────────────
// INIT — aguarda DOM + scripts carregados
// ──────────────────────────────────────────────────────────────
function initPrismaticBurst() {
  const canvas = document.getElementById('prismatic-canvas');
  if (!canvas || typeof PrismaticBurst === 'undefined') return;

  const pb = new PrismaticBurst(canvas, {
    animationType: 'rotate3d',
    intensity: 3.7,
    speed: 0.55,
    distort: 4.8,
    paused: false,
    offset: { x: 0, y: 0 },
    hoverDampness: 0.25,
    rayCount: 0,
    mixBlendMode: 'lighten',
    colors: ['#a855f7', '#7c3aed', '#6366f1', '#a855f7'],
  });

  // Pausar o WebGL loop do hero quando ele não estiver visível na tela
  ScrollTrigger.create({
    trigger: '#hero',
    start: 'top bottom',
    end: 'bottom top',
    onEnter: () => pb.paused = false,
    onLeave: () => pb.paused = true,
    onEnterBack: () => pb.paused = false,
    onLeaveBack: () => pb.paused = true,
  });
}

function init() {
  initLenis();
  initLoader();
  initHero();
  initMarquee();
  initLogoTicker();
  initCards();
  initCounters();
  initParallax();
  initSteps();
  initGlassSpotlight();
  initMagneticButtons();
  initNavScroll();
  initPricingTabs();
  initFAQ();
  initVideoModal();
  initSmoothAnchors();
  initStaggeredMenu();
  initDock();
  // Funções de otimização
  initFloatPause();
  initBorderSpinPause();
  initNewsletterFeedback();
}

// Com defer, o DOM já está pronto quando o script executa
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}

// WebGL é inicializado somente após TODOS os recursos (imagens, fontes) carregarem
// para não competir com FCP/LCP na thread principal
window.addEventListener('load', () => {
  initPrismaticBurst();
});

// ──────────────────────────────────────────────────────────────
// STAGGERED MOBILE MENU
// ──────────────────────────────────────────────────────────────
function initStaggeredMenu() {
  const toggleBtn = document.getElementById('sm-toggle');
  const panel = document.getElementById('staggered-menu-panel');
  const wrapper = document.getElementById('staggered-menu-wrapper');
  const textInner = document.getElementById('sm-toggle-textInner');



  const preLayers = Array.from(document.querySelectorAll('.sm-prelayer'));
  const preContainer = document.getElementById('sm-prelayers');

  if (!toggleBtn || !panel || !wrapper) return;

  let isOpen = false;
  let isBusy = false;

  const itemEls = Array.from(panel.querySelectorAll('.sm-panel-itemLabel'));
  const numberEls = Array.from(panel.querySelectorAll('.sm-panel-list[data-numbering] .sm-panel-itemWrap')); // aproximado, usaremos after element
  const socialTitle = panel.querySelector('.sm-socials-title');
  const socialLinks = Array.from(panel.querySelectorAll('.sm-socials-link'));

  // Initial Setup
  gsap.set([panel, ...preLayers], { xPercent: 100, opacity: 1 });
  if (preContainer) {
    gsap.set(preContainer, { xPercent: 0, opacity: 1 });
  }



  gsap.set(textInner, { yPercent: 0 });

  // Timelines
  let openTl = null;

  function buildOpenTimeline() {
    if (openTl) openTl.kill();
    gsap.killTweensOf([panel, ...preLayers]);

    if (itemEls.length) gsap.set(itemEls, { yPercent: 140, rotate: 10 });
    if (socialTitle) gsap.set(socialTitle, { opacity: 0 });
    if (socialLinks.length) gsap.set(socialLinks, { y: 25, opacity: 0 });

    const tl = gsap.timeline({ paused: true });

    preLayers.forEach((el, i) => {
      tl.fromTo(el, { xPercent: 100 }, { xPercent: 0, duration: 0.5, ease: 'power4.out' }, i * 0.07);
    });

    const lastTime = preLayers.length ? (preLayers.length - 1) * 0.07 : 0;
    const panelInsertTime = lastTime + (preLayers.length ? 0.08 : 0);
    const panelDuration = 0.65;

    tl.fromTo(panel, { xPercent: 100 }, { xPercent: 0, duration: panelDuration, ease: 'power4.out' }, panelInsertTime);

    if (itemEls.length) {
      const itemsStart = panelInsertTime + panelDuration * 0.15;
      tl.to(itemEls, {
        yPercent: 0,
        rotate: 0,
        duration: 1,
        ease: 'power4.out',
        stagger: { each: 0.1, from: 'start' }
      }, itemsStart);
    }

    if (socialTitle || socialLinks.length) {
       const socialsStart = panelInsertTime + panelDuration * 0.4;
       if (socialTitle) tl.to(socialTitle, { opacity: 1, duration: 0.5, ease: 'power2.out' }, socialsStart);
       if (socialLinks.length) tl.to(socialLinks, { y: 0, opacity: 1, duration: 0.55, ease: 'power3.out', stagger: { each: 0.08, from: 'start' } }, socialsStart + 0.04);
    }
    openTl = tl;
    return tl;
  }

  function playClose() {
    if (openTl) { openTl.kill(); openTl = null; }
    
    document.body.style.overflow = '';
    if (lenis) lenis.start();
    
    const all = [...preLayers, panel];
    gsap.killTweensOf(all);
    gsap.to(all, {
      xPercent: 100,
      duration: 0.32,
      ease: 'power3.in',
      overwrite: 'auto',
      onComplete: () => {
        wrapper.removeAttribute('data-open');
        isBusy = false;
      }
    });

    // Reset items specifically so hovering over empty screen doesn't show them if pointer events mess up
    if (itemEls.length) gsap.set(itemEls, { yPercent: 140, rotate: 10 });
  }

  function animateText(opening) {
    if (!textInner) return;
    const currentLabel = opening ? 'Menu' : 'Close';
    const targetLabel = opening ? 'Close' : 'Menu';
    const cycles = 3;
    const seq = [currentLabel];
    let last = currentLabel;
    for (let i = 0; i < cycles; i++) {
      last = last === 'Menu' ? 'Close' : 'Menu';
      seq.push(last);
    }
    if (last !== targetLabel) seq.push(targetLabel);
    seq.push(targetLabel);
    
    textInner.innerHTML = '';
    seq.forEach(str => {
      const sp = document.createElement('span');
      sp.className = 'sm-toggle-line';
      sp.textContent = str;
      textInner.appendChild(sp);
    });

    gsap.set(textInner, { yPercent: 0 });
    const lineCount = seq.length;
    const finalShift = ((lineCount - 1) / lineCount) * 100;
    
    gsap.to(textInner, {
      yPercent: -finalShift,
      duration: 0.5 + lineCount * 0.07,
      ease: 'power4.out'
    });
  }

  function toggleMenu() {
    if (isBusy) return;
    const target = !isOpen;
    isOpen = target;
    isBusy = true;
    
    if (target) {
      document.body.style.overflow = 'hidden';
      if (lenis) lenis.stop();
      wrapper.setAttribute('data-open', 'true');
      const tl = buildOpenTimeline();
      tl.eventCallback('onComplete', () => { isBusy = false; });
      tl.play(0);

      gsap.to(toggleBtn, { color: '#E040FB', duration: 0.3 }); // highlight to pink
    } else {
      playClose();

      gsap.to(toggleBtn, { color: '#fff', duration: 0.3 });
    }
    animateText(target);
  }

  function closeMenu() {
    if (!isOpen) return;
    isOpen = false;
    isBusy = true;
    playClose();

    gsap.to(toggleBtn, { color: '#fff', duration: 0.3 });
    animateText(false);
  }

  toggleBtn.addEventListener('click', toggleMenu);

  document.addEventListener('mousedown', e => {
    if (isOpen && panel && !panel.contains(e.target) && !toggleBtn.contains(e.target)) {
      closeMenu();
    }
  });

  // Fechar ao clicar em um link
  panel.querySelectorAll('.nav-link').forEach(link => {
    link.addEventListener('click', closeMenu);
  });
}
