// assets/js/app.js
(function () {
  const C = window.LP_CONFIG || {};
  const root = document.documentElement;

  // Variáveis de cor
  root.style.setProperty("--base",  C.baseColor  || "#0A0E19");
  root.style.setProperty("--brand", C.brandColor || "#26194E");
  root.style.setProperty("--glow",  C.glowColor  || "#43D9E8");

  // Dinâmicos básicos
  document.title = C.title || document.title;
  document.querySelectorAll("[data-dyn='brand']").forEach(el => el.textContent = C.brand || 'Sua Marca');
  document.querySelectorAll("[data-dyn='whatsappLink']").forEach(el => el.href = C.whatsappLink || '#');
  document.querySelector("[data-dyn='year']")?.append(new Date().getFullYear());
  ["checkoutLink","checkoutBasic","checkoutPro","checkoutPremium"].forEach(k=>{
    const el = document.querySelector(`[data-dyn='${k}']`);
    if(el && C[k]) el.href = C[k];
  });

  // Pricing toggle
  let yearly = false;
  const toggle = document.getElementById("togglePricing");
  const dot = toggle?.querySelector(".dot");
  const updatePrices = () => {
    const ref = yearly ? C.prices.yearly : C.prices.monthly;
    ["basic","pro","premium"].forEach(plan=>{
      document.querySelectorAll(`[data-price='${plan}'], .pv[data-price='${plan}']`).forEach(el=>{
        el.innerHTML = `R$ ${ref[plan]}<span class="suf">/mês</span>`;
      });
    });
  };
  toggle?.addEventListener("click", () => {
    yearly = !yearly;
    dot?.classList.toggle("translate-x-1");
    dot?.classList.toggle("translate-x-7");
    updatePrices();
  });
  updatePrices();

  // Modal vídeo
  const modal = document.getElementById("videoModal");
  const frame = document.getElementById("videoFrame");
  const openVideo = () => { if(!C.videoUrl) return; frame.src = C.videoUrl; modal.classList.replace("hidden","flex"); document.body.style.overflow="hidden"; };
  const closeVideo = () => { modal.classList.replace("flex","hidden"); frame.src=""; document.body.style.overflow=""; };
  document.getElementById("btnOpenVideo")?.addEventListener("click", openVideo);
  document.getElementById("btnOpenVideo2")?.addEventListener("click", openVideo);
  document.getElementById("btnCloseVideo")?.addEventListener("click", closeVideo);
  modal?.addEventListener("click",(e)=>{ if(e.target===modal) closeVideo(); });

  // Lead form
  const form = document.getElementById("leadForm");
  const msg = document.getElementById("leadMsg");
  form?.addEventListener("submit", async (e)=>{
    e.preventDefault();
    msg.textContent = "Enviando...";
    const fd = new FormData(form);
    const payload = {
      nome: fd.get("nome"),
      email: fd.get("email"),
      utm: Object.fromEntries(new URLSearchParams(location.search).entries()),
      page: location.href,
      ts: new Date().toISOString()
    };
    try{
      const res = await fetch(C.leadWebhook, { method:"POST", headers:{ "Content-Type":"application/json" }, body: JSON.stringify(payload) });
      if(!res.ok) throw new Error("bad");
      msg.textContent = "Tudo certo! Te enviamos o material 🎉";
      form.reset();
    }catch(err){
      msg.textContent = "Falhou agora. Tenta novamente em instantes.";
      console.error(err);
    }
  });

  // Marquee render
(function renderMarquee(){
  const track = document.getElementById("marqueeTrack");
  if (!track) return;

  // 👇 Se já tem itens no HTML, não renderiza nada (evita duplicar)
  if (track.children.length > 0) return;

  const items = (window.LP_CONFIG?.marqueeItems || []);
  const all = items.concat(items);
  all.forEach(it => {
    const pill = document.createElement("div");
    pill.className = "pill";
    pill.textContent = it.text || "";
    track.appendChild(pill);
  });
})();


  // Partículas leves
  const cvs = document.getElementById("fxParticles");
  if (cvs && cvs.getContext) {
    const ctx = cvs.getContext("2d");
    let w,h,particles=[];
    const DPR = window.devicePixelRatio||1;
    const resize = ()=>{
      w = cvs.clientWidth; h = cvs.clientHeight;
      cvs.width = w*DPR; cvs.height = h*DPR;
      ctx.setTransform(DPR,0,0,DPR,0,0);
      // reset
      particles = Array.from({length: Math.min(140, Math.floor((w*h)/12000))}).map(()=>({
        x: Math.random()*w, y: Math.random()*h,
        vx: (Math.random()-.5)*.3, vy:(Math.random()-.5)*.3,
        r: Math.random()*1.2 + .4, a: Math.random()*.5 + .1
      }));
    };
    const tick = ()=>{
      ctx.clearRect(0,0,w,h);
      particles.forEach(p=>{
        p.x+=p.vx; p.y+=p.vy;
        if(p.x<0||p.x>w) p.vx*=-1;
        if(p.y<0||p.y>h) p.vy*=-1;
        ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,Math.PI*2);
        ctx.fillStyle = `rgba(${hexToRgb(C.glowColor||"#43D9E8")},${p.a})`;
        ctx.fill();
      });
      requestAnimationFrame(tick);
    };
    window.addEventListener("resize", resize);
    resize(); tick();
  }
  function hexToRgb(hex){
    const m = hex.replace('#',''); const bigint = parseInt(m,16);
    if(m.length===6){ return [(bigint>>16)&255,(bigint>>8)&255,bigint&255].join(','); }
    return "67,217,232";
  }

  // Tilt 3D
  document.querySelectorAll(".card-tilt").forEach((wrap)=>{
    const card = wrap.querySelector(".card");
    wrap.addEventListener("mousemove",(e)=>{
      const b = wrap.getBoundingClientRect();
      const px = (e.clientX-b.left)/b.width - .5;
      const py = (e.clientY-b.top)/b.height - .5;
      card.style.transform = `rotateX(${py*-10}deg) rotateY(${px*10}deg) translateZ(0)`;
    });
    wrap.addEventListener("mouseleave",()=> card.style.transform = "");
  });

  // Scroll-reveal
  const io = new IntersectionObserver((entries)=>{
    entries.forEach(en=>{
      if(en.isIntersecting){
        en.target.classList.add("in");
        io.unobserve(en.target);
      }
    })
  }, { threshold:.15 });
  document.querySelectorAll(".reveal").forEach(el=> io.observe(el));
})();
