Linha Clássica.

Mesma lente. Mesmo resultado.
Preço especial por tempo limitado.

Ver os óculos

Linha Clássica

Três lentes, três momentos do dia. Escolha a sua.

DEEP Day

DEEP Day

★★★★★ (247)

R$ 247,00

DEEP Dusk

DEEP Dusk

★★★★★ (487)

R$ 247,00

DEEP Night

DEEP Night

★★★★★ (312)

R$ 247,00

DEEP Day

DEEP Day

Sem caixinha e paninho

★★★★★ (189)

R$ 197,00

R$ 247 3x de R$78,22

Leve 2 por R$444,60

10% de desconto — escolha 2 modelos diferentes ou iguais

Continuar comprando
Frete grátis3x sem jurosGarantia 7 dias
Continuar comprando

Finalizar compra

Nome obrigatório

E-mail inválido

WhatsApp com DDD

CPF inválido

CEP inválido

Endereço obrigatório

Informe o número

Cidade obrigatória

Estado obrigatório

SubtotalR$ 247,00
TotalR$ 247,00

Pagamento

O QR Code PIX será gerado ao finalizar.

Desconto · 5% OFF

Modelos Femininos

Armação tartaruga delicada. Design exclusivo.

DEEP Day Feminino
Pré-venda

DEEP Day

★★★★★ (novo)

R$ 397 R$ 347,00

DEEP Dusk Feminino
Pré-venda

DEEP Dusk

★★★★★ (novo)

R$ 397 R$ 347,00

Outros Modelos

Mesma tecnologia. Outro estilo.

DEEP Air

Deep Air

30 unidades · Reduz o ronco

★★★★★ (89)

R$ 67,00

DEEP Day

DEEP Day

Sem caixinha e paninho

★★★★★ (189)

R$ 197,00

DEEP Angular

DEEP Angular

★★★★★ (218)

R$ 247,00

Dusk Angular
Esgotado

Dusk Angular

★★★★★ (342)

R$ 247,00

DEEP Day
Esgotado

DEEP Day

★★★★★ (163)

R$ 247,00

Night Angular

Night Angular

★★★★★ (276)

R$ 247,00

Quem usa, sabe

O sono voltou.

Cliente

"Eu tenho que acordar cedo todos os dias. Deitava na cama, mas demorava a dormir. Hoje eu apago até 22h30. O DEEP Dusk foi um dos melhores investimentos."

Gabriela

São Paulo

DEEP Dusk

Cliente

"Uso o Day durante o dia e principalmente nas horas de tela. Meus olhos ficam muito menos cansados e chego no fim do dia bem melhor."

Ially

Aracaju

DEEP Day

Cliente

"Trabalho com telas e tinha muita ardência nos olhos. O DEEP Day está me salvando."

Joan

Santa Catarina

DEEP Day

Como usar

Uma lente para cada momento.

Toque no card e veja como é olhar por cada lente

Clique aqui

Amarelo

Para o dia e para telas.

Ideal para quem passa muito tempo em telas ou sob luz artificial. Ajuda com dores de cabeça, desconforto visual/ardência nos olhos. Você chega à noite com o cortisol mais baixo.

Uso recomendado

Durante o dia e à noite, especialmente em períodos prolongados em frente às telas.

Clique aqui

Coral

A lente mais versátil.

Para o fim da tarde e para a noite, sem escurecer demais a visão. Já estimula a produção natural de melatonina de forma suave. Perfeita para assistir TV, usar telas, socializar, sair e dirigir à noite.

Uso recomendado

Fim de tarde e noite, especialmente quando você ainda precisa manter uma boa percepção do ambiente.

Clique aqui

Vermelho

Hibernação total.

A opção de bloqueio mais intenso para o período antes de dormir. A lente vermelha induz ao sono, deixando o ambiente mais escuro.

Uso recomendado

De 1 a 2 horas antes de dormir. Não indicada para dirigir e sair, porque escurece bastante a visão.

Pós-venda

Rastreie seu pedido

Digite o código de rastreio que você recebeu no WhatsApp.

Siga-nos no Instagram

Seguir

FAQs

A DEEP é a primeira empresa brasileira especializada em sono, trazendo produtos desenvolvidos para melhorar suas noites e o seu bem-estar. Nosso foco é ajudar o brasileiro a dormir melhor e, consequentemente, ter uma vida mais saudável, produtiva e com mais disposição.

Day (âmbar): Filtra a luz azul de telas durante o dia, reduz fadiga ocular e ajuda a manter o cortisol mais baixo.
Dusk (coral): Para o fim de tarde, estimula a produção natural de melatonina de forma suave.
Night (vermelha): Bloqueio total de luz azul e verde, ideal 1-3h antes de dormir para induzir o sono profundo.

Sim! Todos os modelos DEEP são fit-over, ou seja, encaixam por cima dos seus óculos de grau. Você não precisa de lente com receita.

De 5 a 15 dias úteis, dependendo da região.

Sim. Garantia de 7 dias após o recebimento. Se não gostar, devolvemos seu dinheiro.

Sim! Parcelamos em até 3x sem juros no cartão de crédito. No PIX, o PIX tem 5% de desconto.

Seu sono merece isso.

Escolha sua lente. Vista antes de dormir. Sinta a diferença na primeira noite.

Ver modelos

Frete grátis · 3x sem juros · Garantia 7 dias

Abrindo câmera…

Âmbar Coral Vermelha
+parcela+' sem juros'; selectedInstallment=3; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +fmt(pv)+sj+''; } sel.innerHTML = html; selectedInstallment=1; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +total+' sem juros').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +parcela+' sem juros'; selectedInstallment=3; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +fmt(v/i)+' sem juros'; } html += ''; for (let i = 4; i <= 12; i++) { html += ''; } sel.innerHTML = html; selectedInstallment=1; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +parcela+' sem juros'; selectedInstallment=3; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +fmt(pv)+sj+''; } sel.innerHTML = html; selectedInstallment=1; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +total+' sem juros').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); } +parcela+' sem juros'; selectedInstallment=3; return; } sel.innerHTML = instOptions.map(o=>'').join(''); } document.getElementById('f-installments').addEventListener('change',e=>{selectedInstallment=parseInt(e.target.value);}); // ===== PAYMENT HELPERS ===== function getProcessPayment() { if(!fbFunctions && window.firebaseModules) { const{getFunctions}=window.firebaseModules; if(fbApp)fbFunctions=getFunctions(fbApp); } if(!fbFunctions||!window.firebaseModules.httpsCallable) throw new Error("Backend offline."); return window.firebaseModules.httpsCallable(fbFunctions,'processPayment'); } function buildDesc() { const glassesDesc = cart.map(key=>{ const p=PD[key]; return p.name+(p.code?' · '+p.code:''); }).join(', '); const nasalDesc = document.getElementById('bump-nasal').checked ? 'Deep Air' : ''; return glassesDesc && nasalDesc ? glassesDesc+' + '+nasalDesc : glassesDesc || nasalDesc; } function buildCartItems() { const items = cart.map(key=>{ const p=PD[key]; return { id:key, name:p.name, code:p.code, price:p.price||DEEP_PRICE, type:key.includes('night')?'red':key.includes('dusk')?'afternoon':'yellow', image:p.img }; }); if(document.getElementById('bump-nasal').checked) items.push({id:'nasal',name:'Deep Air',code:'DDN-01',price:NASAL_PRICE,type:'nasal',image:''}); return items; } function buildFormData() { const form = getForm(); const p = calcPrice(); return {...form, brand:'DEEP', couponCode:isCouponValid?couponCode:null, campaign:CAMPAIGN.c||null, remarketingId:CAMPAIGN.r||null, cartItems:buildCartItems(), selectedBumps:document.getElementById('bump-nasal').checked?['nasal']:[], originalPrice:p.productsTotal, finalPrice:p.finalPrice }; } const rejectMsg = sd => { const m={cc_rejected_insufficient_amount:'Saldo ou limite insuficiente.',cc_rejected_bad_filled_card_number:'Número do cartão incorreto.',cc_rejected_bad_filled_date:'Data de validade incorreta.',cc_rejected_bad_filled_security_code:'CVV incorreto.',cc_rejected_call_for_authorize:'Ligue para o banco e autorize.',cc_rejected_high_risk:'Recusado por segurança. Tente outro cartão ou PIX.',cc_rejected_max_attempts:'Muitas tentativas. Aguarde alguns minutos.'}; return m[sd]||'Pagamento recusado. Tente outro cartão ou pague no PIX.'; }; // ===== OVERLAYS ===== function showOverlay(id) { document.getElementById(id).style.display='flex'; } function hideOverlay(id) { document.getElementById(id).style.display='none'; } function dismissOverlay() { ['ov-processing','ov-pix','ov-approved','ov-analysis','ov-rejected'].forEach(id=>hideOverlay(id)); currentStatus=null; } function handlePaymentResponse(r) { hideOverlay('ov-processing'); if(r&&r.success&&r.status==='approved') { currentPaymentId=r.id; currentStatus='approved'; showApproved(); try{radar.ev('payres',{s:'approved',v:calcPrice().finalPrice});radar.flush(false);}catch(e){} return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')&&r.qr_code_base64) { currentPaymentId=r.id; pixData={qrCode:r.qr_code,qrCodeBase64:r.qr_code_base64}; currentStatus='pix_pending'; showPixQR(); try{radar.ev('pix',{v:calcPrice().finalPrice});radar.flush(false);}catch(e){} startPolling(); return; } if(r&&r.success&&(r.status==='pending'||r.status==='in_process')) { currentPaymentId=r.id; currentStatus='analysis'; showOverlay('ov-analysis'); startPolling(); return; } currentStatus='rejected'; document.getElementById('reject-msg').textContent=rejectMsg(r&&r.status_detail); showOverlay('ov-rejected'); try{radar.ev('payres',{s:'rejected',detail:(r&&r.status_detail)||''});radar.flush(false);}catch(e){} } function showPixQR() { document.getElementById('pix-qr-img').src='data:image/png;base64,'+pixData.qrCodeBase64; document.getElementById('pix-code').value=pixData.qrCode; showOverlay('ov-pix'); } function showApproved() { const form=getForm(); const fn=(form.name||'').trim().split(/\s+/)[0]||'membro'; document.getElementById('ap-name').textContent=fn; document.getElementById('ap-email').textContent=form.email; document.getElementById('ap-order').textContent=currentPaymentId?'#'+String(currentPaymentId).slice(-8):''; const waMsg='Olá! Acabei de comprar na DEEP e meu pagamento foi aprovado. Quero confirmar o pedido e o rastreio. ('+buildDesc()+')'; document.getElementById('ap-wa-link').href='https://wa.me/'+WHATSAPP_SUPPORT+'?text='+encodeURIComponent(waMsg); showOverlay('ov-approved'); // confetti if(typeof window.confetti==='function'){const c=window.confetti;const colors=['#ffb13b','#ff4d3d','#ffffff','#ffd27a'];c({particleCount:200,origin:{x:.5,y:.5},spread:110,startVelocity:52,colors,ticks:80,zIndex:1300});const end=Date.now()+4000;const iv=setInterval(()=>{if(Date.now()-end>0){clearInterval(iv);return;}c({particleCount:40,origin:{x:Math.random()*.3+.05,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});c({particleCount:40,origin:{x:Math.random()*.3+.65,y:Math.random()*.4},spread:360,colors,ticks:80,zIndex:1300});},230);} // save + redirect try{sessionStorage.setItem('selva_purchase',JSON.stringify({v:calcPrice().finalPrice,id:currentPaymentId,wa:document.getElementById('ap-wa-link').href,b:'deep',n:fn}));}catch(e){} setTimeout(()=>{ window.location.href='/obrigado'; },8000); } // status polling let pollIv = null; function startPolling() { if(pollIv) clearInterval(pollIv); pollIv = setInterval(async()=>{ try { if(!fbFunctions) return; const cs = window.firebaseModules.httpsCallable(fbFunctions,'checkPaymentStatus'); const r = await cs({paymentId:currentPaymentId}); if(r.data&&(r.data.status==='approved'||r.data.status==='paid')) { clearInterval(pollIv); hideOverlay('ov-pix'); hideOverlay('ov-analysis'); currentStatus='approved'; showApproved(); } } catch(e){} },3000); } // ===== LEAD NOTIFICATION ===== function sendLead() { if(leadSent) return; leadSent=true; try { if(!SMOKE && fbFunctions && window.firebaseModules.httpsCallable) { const notifyLead = window.firebaseModules.httpsCallable(fbFunctions,'notifyLead'); const form=getForm(); notifyLead({name:form.name,email:form.email,phone:form.phone,city:form.city,cartSummary:buildDesc(),total:calcPrice().finalPrice,source:'deep_checkout',campaign:CAMPAIGN.c||null}).catch(()=>{}); } } catch(e){} } // ===== PAY WITH PIX ===== async function payWithPix() { if(!validateForm()) return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); if(!validCPF(cpfDigits)){alert('CPF errado, revise.');return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:'pix',payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:1,productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== PAY WITH CARD ===== async function payWithCard() { if(!validateForm()) return; if(currentStatus==='processing') return; const form=getForm(); const cpfDigits=(form.cpf||'').replace(/\D/g,''); const cardErr = document.getElementById('card-field-error'); if(!mpFields||!mpFields.mp){cardErr.textContent='Recarregue a página.';cardErr.style.display='block';return;} const holderName=document.getElementById('f-cardholder').value.trim(); if(!holderName){cardErr.textContent='Preencha o nome no cartão.';cardErr.style.display='block';return;} if(!selectedInstallment||!cardPmId){cardErr.textContent='Digite o cartão e escolha parcelas.';cardErr.style.display='block';return;} cardErr.style.display='none'; let token; try { token=await mpFields.mp.fields.createCardToken({cardholderName:holderName,identificationType:'CPF',identificationNumber:cpfDigits}); } catch(err){ cardErr.textContent='Confira número, validade e CVV.';cardErr.style.display='block';return; } if(!token||!token.id){cardErr.textContent='Confira os dados do cartão.';cardErr.style.display='block';return;} sendLead(); currentStatus='processing'; showOverlay('ov-processing'); try { const processPayment=getProcessPayment(); const p=calcPrice(); const r=await processPayment({token:token.id,transaction_amount:p.finalPrice,description:'Pedido DEEP: '+buildDesc().substring(0,200),payment_method_id:cardPmId,issuer_id:cardIssuerId,payer:{email:form.email,identification:{type:'CPF',number:cpfDigits}},installments:Number(selectedInstallment),productType:(()=>{const ci=buildCartItems();return ci.length>1?'combo':ci[0]?.type||'nasal';})(),formData:buildFormData()}); handlePaymentResponse(r.data); } catch(err) { hideOverlay('ov-processing');currentStatus='rejected';showOverlay('ov-rejected'); try{radar.ev('payerr',{msg:String(err.message||err.code||err).slice(0,150)});radar.flush(false);}catch(e){} } } // ===== FINALIZAR BUTTON ===== document.getElementById('btn-finalizar').addEventListener('click', ()=>{ if(payMethod==='pix') payWithPix(); else payWithCard(); }); const detail = document.getElementById('product-detail'); let activeCard = null; document.querySelectorAll('.product-card[data-product]').forEach(card => { card.addEventListener('click', () => { const key = card.dataset.product; const p = PD[key]; if (!p) return; if (card.dataset.soldOut) return; // add to cart (permite mesmo modelo 2x) cart.push(key); card.classList.add('is-active'); // show last-added product in detail if (activeCard) activeCard.classList.remove('is-active'); activeCard = card; card.classList.add('is-active'); const pdScroll = document.getElementById('pd-scroll'); const pdDots = document.getElementById('pd-dots'); const allImgs = (p.imgs && p.imgs.length > 1) ? p.imgs : [p.img]; pdScroll.innerHTML = allImgs.map(src => '
'+p.name+'
').join(''); pdScroll.scrollLeft = 0; if (allImgs.length > 1) { pdDots.innerHTML = allImgs.map((_,i) => '').join(''); pdDots.classList.remove('hidden'); pdDots.querySelectorAll('button').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); const gi = parseInt(b.dataset.gi); pdScroll.scrollTo({ left: gi * pdScroll.offsetWidth, behavior: 'smooth' }); })); // swipe dot sync if (pdScroll._scrollHandler) pdScroll.removeEventListener('scroll', pdScroll._scrollHandler); pdScroll._scrollHandler = () => { const ci = Math.round(pdScroll.scrollLeft / pdScroll.offsetWidth); pdDots.querySelectorAll('button').forEach((d,j) => { d.className = 'w-2.5 h-2.5 rounded-full transition-colors '+(j===ci?'bg-charcoal':'bg-border'); }); }; pdScroll.addEventListener('scroll', pdScroll._scrollHandler, { passive: true }); // isolate touch from parent let sx=0; pdScroll.addEventListener('touchstart', e => { sx=e.touches[0].clientX; }, { passive:true }); pdScroll.addEventListener('touchmove', e => { if(Math.abs(e.touches[0].clientX-sx)>8) e.stopPropagation(); }, { passive:false }); } else { pdDots.innerHTML = ''; pdDots.classList.add('hidden'); } document.getElementById('pd-name').textContent = p.name; document.getElementById('pd-code').textContent = p.code; document.getElementById('pd-desc').textContent = p.desc; const sp = document.getElementById('pd-specs'); sp.innerHTML = p.specs.map(s => '

'+s[0]+'

'+s[1]+'

').join(''); const pp = p.price||DEEP_PRICE; document.getElementById('pd-oldprice').textContent = 'R$'+(pp+50); document.getElementById('pd-price').innerHTML = 'R$ '+pp; document.getElementById('pd-installments').textContent = '3x de R$'+(pp/3).toFixed(2).replace('.',','); // move detail panel to correct section const section = card.closest('section'); if (section && !section.contains(detail)) { section.querySelector('.max-w-6xl').appendChild(detail); } renderCart(); detail.classList.add('open'); setTimeout(() => detail.scrollIntoView({ behavior:'smooth', block:'nearest' }), 80); // auto-fill saved coupon setTimeout(() => { const saved = sessionStorage.getItem('deep_coupon'); const ci = document.getElementById('ck-coupon'); if (saved && ci && !ci.value) { ci.value = saved; applyCoupon(); } }, 200); }); }); // ===== LENS VIEW ===== const LENS = { amber:{ label:'Âmbar', sub:'DIA · TELAS', tint:'240,196,71', bri:1.12 }, coral:{ label:'Coral', sub:'TARDE · TRANSIÇÃO', tint:'240,132,54', bri:1.14 }, red: { label:'Vermelha', sub:'NOITE · SONO', tint:'212,16,29', bri:1.22 }, }; // --- Lens filter overlay (page tint) + card glow --- function showLensFilter(color) { const overlay = document.getElementById('lens-filter-overlay'); const colorEl = document.getElementById('lens-filter-color'); const tints = { amber:'rgba(240,196,71,0.35)', coral:'rgba(240,132,54,0.4)', red:'rgba(180,20,20,0.45)' }; colorEl.style.background = tints[color] || tints.amber; overlay.style.display = 'block'; requestAnimationFrame(() => overlay.style.opacity = '1'); // glow on active card document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); const active = document.querySelector('.lens-card[data-lens="'+color+'"]'); if (active) active.classList.add('glow-'+color); } function hideLensFilter() { const overlay = document.getElementById('lens-filter-overlay'); overlay.style.opacity = '0'; setTimeout(() => overlay.style.display = 'none', 300); document.querySelectorAll('.lens-card').forEach(c => c.classList.remove('glow-amber','glow-coral','glow-red')); } function toggleFaq(btn) { const body = btn.nextElementSibling; const icon = btn.querySelector('.faq-icon'); const open = body.style.maxHeight && body.style.maxHeight !== '0px'; // close all document.querySelectorAll('.faq-body').forEach(b => b.style.maxHeight = '0px'); document.querySelectorAll('.faq-icon').forEach(i => { i.textContent = '+'; i.style.transform = 'rotate(0)'; }); if (!open) { body.style.maxHeight = body.scrollHeight + 'px'; icon.textContent = '−'; icon.style.transform = 'rotate(180deg)'; } } function trackOrder() { const input = document.getElementById('tracking-input'); const code = input.value.trim(); const err = document.getElementById('tracking-err'); if (!code || code.length < 5) { err.style.display = 'block'; return; } err.style.display = 'none'; window.open('https://rastreamento.superfrete.com/?code=' + encodeURIComponent(code), '_blank'); } document.getElementById('tracking-input').addEventListener('keydown', function(e) { if (e.key === 'Enter') trackOrder(); }); let lvStream=null, lvCurrent='amber'; function openLens(key) { const lv=document.getElementById('lens-view'); lv.classList.add('open'); document.body.style.overflow='hidden'; switchTint(key||'amber'); startCam(); } function closeLens() { const lv=document.getElementById('lens-view'); lv.classList.remove('open'); document.body.style.overflow=''; if(lvStream){lvStream.getTracks().forEach(t=>t.stop());lvStream=null;} document.getElementById('lv-status').textContent='Abrindo câmera…'; document.getElementById('lv-status').style.display='flex'; document.getElementById('lv-tint').style.opacity='0'; } function switchTint(key) { lvCurrent=key; const L=LENS[key]; document.getElementById('lv-tint').style.background='rgb('+L.tint+')'; document.getElementById('lv-label').textContent='Lente '+L.label; document.getElementById('lv-sub').textContent=L.sub; const vid=document.getElementById('lv-video'); vid.style.filter='saturate(1.18) contrast(1.05) brightness('+L.bri+')'; document.querySelectorAll('.tint-btn').forEach(b=>b.classList.toggle('active',b.dataset.tint===key)); document.querySelectorAll('.tint-label').forEach(l=>{l.style.opacity=l.dataset.for===key?'1':'0';l.style.position=l.dataset.for===key?'static':'absolute';}); } async function startCam() { const vid=document.getElementById('lv-video'); const status=document.getElementById('lv-status'); try{ lvStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'},width:{ideal:1280},height:{ideal:720}},audio:false}); vid.srcObject=lvStream; vid.onloadeddata=()=>{ status.style.display='none'; document.getElementById('lv-tint').style.opacity='1'; }; }catch(e){ status.textContent='Câmera não disponível neste dispositivo.'; } } // ===== POPUP SYSTEM ===== function closePopup(id) { document.getElementById(id).classList.remove('show'); document.body.style.overflow = ''; } function showPopup(id) { document.getElementById(id).classList.add('show'); document.body.style.overflow = 'hidden'; } function saveCoupon(code) { sessionStorage.setItem('deep_coupon', code); const ci = document.getElementById('ck-coupon'); if (ci) { ci.value = code; applyCoupon(); } } // --- Popup 2: Lead Capture --- (function() { if (sessionStorage.getItem('deep_p2')) return; if (CAMPAIGN.isInfluencer) return; let fired=false; const t0=Date.now(); function tryFire(){ if(fired) return; if(Date.now()-t0<30000) return; fired=true; sessionStorage.setItem('deep_p2','1'); showPopup('popup-lead'); } window.addEventListener('scroll',()=>{ const pct=(window.scrollY+window.innerHeight)/document.body.scrollHeight; if(pct>.55) tryFire(); }); setTimeout(tryFire,45000); let lastY=0; window.addEventListener('scroll',()=>{ if(window.scrollY<80&&lastY>250) tryFire(); lastY=window.scrollY; }); })(); function submitLead(){ const name=document.getElementById('lead-name').value.trim(); const wpp=document.getElementById('lead-wpp').value.replace(/\D/g,''); const email=document.getElementById('lead-email').value.trim(); if(!name||wpp.length<10||!email.includes('@')){ document.getElementById('lead-err').style.display='block'; return; } sessionStorage.setItem('deep_lead_name',name); sessionStorage.setItem('deep_lead_wpp',wpp); sessionStorage.setItem('deep_lead_email',email); // loading steps document.getElementById('lead-form').style.display='none'; document.getElementById('lead-loading').style.display='block'; ['ls1','ls2','ls3'].forEach((id,i)=>{ setTimeout(()=>document.getElementById(id).classList.add('on'), i*550); setTimeout(()=>document.getElementById(id).classList.add('done'), i*550+350); }); // reveal + auto-close setTimeout(()=>{ document.getElementById('lead-loading').style.display='none'; document.getElementById('lead-ok').style.display='block'; if(!document.getElementById('ck-coupon').value || !isCouponValid) saveCoupon('BOASVINDAS5'); }, 2000); }