/* ============================================================
   ARMÁRIO PERFEITO — interações & animações
   ============================================================ */
(function(){
  "use strict";
  const reduce = window.matchMedia('(prefers-reduced-motion:reduce)').matches;
  const finePointer = window.matchMedia('(hover:hover) and (pointer:fine)').matches;

  /* ---- Scroll progress + header shrink ---- */
  const header = document.querySelector('.site-header');
  const progress = document.querySelector('.scroll-progress');
  function onScroll(){
    const y = window.scrollY || document.documentElement.scrollTop;
    if(header) header.classList.toggle('scrolled', y > 40);
    if(progress){
      const h = document.documentElement.scrollHeight - window.innerHeight;
      progress.style.width = (h>0 ? (y/h*100) : 0) + '%';
    }
  }
  window.addEventListener('scroll', onScroll, {passive:true});
  onScroll();

  /* ---- Reveal on scroll ---- */
  const revealEls = document.querySelectorAll('[data-reveal]');
  if('IntersectionObserver' in window && !reduce){
    const io = new IntersectionObserver((entries)=>{
      entries.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add('in'); io.unobserve(e.target); } });
    },{threshold:0.12, rootMargin:'0px 0px -8% 0px'});
    revealEls.forEach(el=>io.observe(el));
    // Failsafe: nothing should ever stay invisible.
    setTimeout(()=>revealEls.forEach(el=>el.classList.add('in')), 2600);
  } else {
    revealEls.forEach(el=>el.classList.add('in'));
  }

  /* ---- Parallax (data-parallax = speed factor) ---- */
  const parallaxEls = [...document.querySelectorAll('[data-parallax]')];
  let ticking = false;
  function applyParallax(){
    const vh = window.innerHeight;
    parallaxEls.forEach(el=>{
      const speed = parseFloat(el.dataset.parallax) || 0.15;
      const rect = el.getBoundingClientRect();
      const center = rect.top + rect.height/2;
      const offset = (center - vh/2);
      el.style.transform = `translate3d(0, ${(-offset*speed).toFixed(1)}px, 0)`;
    });
    ticking = false;
  }
  if(parallaxEls.length && !reduce){
    window.addEventListener('scroll', ()=>{ if(!ticking){ requestAnimationFrame(applyParallax); ticking=true; } }, {passive:true});
    applyParallax();
  }

  /* ---- 3D tilt cards ---- */
  if(finePointer && !reduce){
    document.querySelectorAll('[data-tilt]').forEach(card=>{
      const inner = card.querySelector('.inner') || card;
      const gloss = card.querySelector('.gloss');
      const max = 9;
      card.addEventListener('pointermove', e=>{
        const r = card.getBoundingClientRect();
        const px = (e.clientX - r.left)/r.width;
        const py = (e.clientY - r.top)/r.height;
        inner.style.transform = `rotateY(${(px-0.5)*max*2}deg) rotateX(${(0.5-py)*max*2}deg) translateZ(6px)`;
        if(gloss){ gloss.style.setProperty('--mx', (px*100)+'%'); gloss.style.setProperty('--my', (py*100)+'%'); }
      });
      card.addEventListener('pointerleave', ()=>{ inner.style.transform=''; });
    });
  }

  /* ---- Marquee: duplicate track for seamless loop ---- */
  document.querySelectorAll('.marquee-track').forEach(track=>{
    track.innerHTML += track.innerHTML;
  });

  /* ---- FAQ accordion ---- */
  document.querySelectorAll('.faq-item').forEach(item=>{
    const q = item.querySelector('.faq-q');
    const a = item.querySelector('.faq-a');
    q.addEventListener('click', ()=>{
      const open = item.classList.contains('open');
      document.querySelectorAll('.faq-item.open').forEach(o=>{
        if(o!==item){ o.classList.remove('open'); o.querySelector('.faq-a').style.maxHeight='0px'; }
      });
      if(open){ item.classList.remove('open'); a.style.maxHeight='0px'; }
      else { item.classList.add('open'); a.style.maxHeight = a.scrollHeight + 'px'; }
    });
  });

  /* ---- Countdown (real, configurable) ----
     Edit TARGET to your launch date/time. */
  const TARGET = new Date('2026-06-05T09:00:00-03:00').getTime();
  const cd = document.querySelector('[data-countdown]');
  if(cd){
    const map = {dias:null,horas:null,minutos:null,segundos:null};
    Object.keys(map).forEach(k=>{ map[k] = cd.querySelector(`[data-cd="${k}"]`); });
    const prev = {};
    function pad(n){ return String(n).padStart(2,'0'); }
    function tick(){
      let diff = TARGET - Date.now();
      const openMsg = cd.parentElement.querySelector('[data-cd-open]');
      if(diff <= 0){
        Object.values(map).forEach(el=>{ if(el) el.textContent='00'; });
        if(openMsg) openMsg.hidden = false;
        return;
      }
      const d = Math.floor(diff/86400000); diff-=d*86400000;
      const h = Math.floor(diff/3600000); diff-=h*3600000;
      const m = Math.floor(diff/60000); diff-=m*60000;
      const s = Math.floor(diff/1000);
      const vals = {dias:pad(d),horas:pad(h),minutos:pad(m),segundos:pad(s)};
      Object.keys(vals).forEach(k=>{
        const el = map[k]; if(!el) return;
        if(prev[k]!==vals[k]){
          el.textContent = vals[k];
          if(!reduce){ el.classList.add('tick'); setTimeout(()=>el.classList.remove('tick'),300); }
          prev[k]=vals[k];
        }
      });
    }
    tick(); setInterval(tick,1000);
  }

  /* ---- Custom cursor ---- */
  if(finePointer && !reduce){
    const dot = document.createElement('div'); dot.className='cursor-dot';
    const ring = document.createElement('div'); ring.className='cursor-ring';
    document.body.append(dot,ring);
    let rx=0,ry=0,dx=0,dy=0;
    document.addEventListener('pointermove', e=>{
      dx=e.clientX; dy=e.clientY;
      dot.style.transform=`translate(${dx}px,${dy}px) translate(-50%,-50%)`;
    });
    (function loop(){
      rx += (dx-rx)*0.18; ry += (dy-ry)*0.18;
      ring.style.transform=`translate(${rx}px,${ry}px) translate(-50%,-50%)`;
      requestAnimationFrame(loop);
    })();
    const hov = 'a,button,.mod-card,.mini-card,.faq-q,.testi,.play-btn,.btn';
    document.querySelectorAll(hov).forEach(el=>{
      el.addEventListener('pointerenter',()=>ring.classList.add('hover'));
      el.addEventListener('pointerleave',()=>ring.classList.remove('hover'));
    });
  }

  /* ---- Smooth anchor scroll for in-page links ---- */
  document.querySelectorAll('a[href^="#"]').forEach(a=>{
    a.addEventListener('click', e=>{
      const id = a.getAttribute('href');
      if(id.length<2) return;
      const t = document.querySelector(id);
      if(t){ e.preventDefault(); window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-70, behavior:'smooth'}); }
    });
  });
})();
