–:–
Acesso privado total
O Lazer mais exclusivo em Conselheiro Lafaiete.
Você adquire um título e tem acesso perma-
nente a piscinas, academia, gastronomia,
esportes e experiências únicas.
Contato direto no WhatsApp
Como funciona na prática?
- Você adquire um título vitalício, que poderá ser revendido após 1 ano de funcionamento.
- Não existe ingresso diário, aqui você não divide espaço com excursão.
- Sua família usa o complexo sempre que quiser, de terça
a domingo. - Estrutura de alto padrão, limitada a 5.000 usuários.
Exclusividade real
da população da região terá acesso ao Villa Rica, apenas 5.000 títulos vitalícios serão comercializados.
Acesso exclusivo apenas para titulares
Sem day use (Ingresso diário)
Venda de apenas a 5.000 títulos.
Um universo de experiências
Seu dia, suas escolhas.
Escolha o que combina com o seu momento: esporte, relaxamento, gastronomia, família e bem-estar.
Corpo e mente
Academia, pilates e spa
Energia e esporte
Quadras, campos e pistas
Lazer e relaxamento
Piscinas, rio lento e bares
Sabores e encontros
Restaurantes e gastronomia
Alegria e descobertas
Universo infantil
Bem-estar e saúde
Sauna, spa e relaxamento
Obras a todo vapor
Conheça de perto
Veja agora, em imagens reais, o avanço da obra.
Obra já avançou quase 40% do prazo total previsto. As próximas fases já estão em execução
e, conforme cada etapa é entregue, os títulos tendem a se valorizar, com previsão total até dezembro de 2028.
Progresso
0%
Bem-estar diário
Eleve sua rotina.
Transforme seu dia.
Imagine começar o dia com um treino na academia com-
pleta, praticar seu esporte favorito no fim de tarde e rela-
xar na sauna antes de voltar para casa. No Villa Rica, o bem-estar não é só de fim de semana, vira parte da sua semana.
Aberto 6 dias por semana. Academia e pilates liberados para todos os titulares e seus dependentes.
Segurança familiar
Sua paz de espírito
é prioridade.
Seus filhos podem brincar com liberdade enquanto você relaxa com tranquilidade.
Monitoramento 24h
Acesso controlado
Você e sua familia seguros
Investimento inteligente
Mais que um título.
Um patrimônio seu.
Seu título é vitalício e hereditário. Um investimento que tende a valorizar.
Vitalício (uso para sempre)
Hereditário (passa para a família)
Valoriza a cada fase entregue
Experiência imersiva
Conheça cada detalhe em 360°
Explore o complexo como se já estivesse lá. Navegue pelos ambientes e descubra o que espera por você.
Tire suas dúvidas
Perguntas frequentes
Sim. O Villa Rica é restrito a titulares, dependentes cadastrados e convidados. Não há day use ou excursões.
O complexo funciona 6 dias por semana (terça a domingo). A estrutura de bem-estar e lazer é pensada para virar rotina.
Conforme as fases do complexo são entregues, os títulos tendem a se valorizar.
Após 1 ano de funcionamento, você pode revender sua cota no mercado.
Pagamento facilitado em até 48x no cartão recorrente, com parcelas que cabem no seu planejamento.
Parcelas a partir de R$ 210,00.
Taxa de manutenção com valor acessível.
Você só começa a pagar após a entrega total da obra.
Academia e pilates já estão inclusos, sem mensalidade extra.
Valor da manutenção:
R$ 190,00 (titular + cônjuge) ou Apenas Titular
+ R$ 50,00 por dependente
Teremos atrações nunca vistas em Lafaiete, previstas para serem entregues até dezembro de de 2028! Que consideremos básico para o seu lazer como:
- Restaurantes e lanchonetes
- Bares e Quiosques
- Churrasqueiras
- Piscina de ondas
- Espaço kids externo
- Piscinas aquecidas indoor
- Piscina infantil aquecida
- Rio lento
- Bar molhado
- Redário
- Playground infantil indoor
- Saunas masculina e feminina
- Academia
- Pilates
- Espaço de dança
- Salão de jogos
- Scoth Bar
- Campo de futebol oficial
- Campos de futebol de 7
- Quadras de vôlei, futebol de salão, basquete e tênis
- Quadras de areia para Beach Tennis
- Pista de caminhada
E muito mais!!!
Na mídia
O Villa Rica já virou notícia
Passe para o lado e clique no card para abrir a matéria em uma nova aba.
Quem decidiu sair na frente
Eles escolheram fazer parte.
Agora é a sua vez.
Garanta antes da próxima valorização.
(function(){ /* ====== ROTATOR COTAS ====== */ (() => { const box = document.getElementById('cotaRotator'); if(!box) return; const items = Array.from(box.querySelectorAll('span')); let i = 0;
setInterval(() => { items[i].classList.remove('active'); i = (i + 1) % items.length; items[i].classList.add('active'); }, 3200); })();
/* ====== QUIZ HTML ====== */ const WHATS_NUMBER = "553137396000"; const VISIT_LINK_MODE = "whatsapp"; const VISIT_URL = "https://complexovillarica.com";
const SHEETS_WEBAPP_URL = "https://script.google.com/macros/s/AKfycbyeoVKodXm-OvOgP1yL_2-6i47zPlsuYijWZGuLLfzNdFJVZw72DroTB-A_o2Rvc1Mx/exec";
const QUESTIONS = [ { id:"q1", type:"text", title:"Qual podemos te chamar?", helper:"" }, { id:"q2", type:"tel", title:"Qual o seu telefone?", helper:"Telefone é obrigatório para continuar." }, { id:"q3", type:"email", title:"Qual o seu e-mail?", helper:"Opcional. Se não quiser informar, marque abaixo." },
{ id:"q4", type:"radio", title:"Você mora em qual cidade?", helper:"Distância influencia em frequência de uso e no plano mais indicado.", options:["Conselheiro Lafaiete","Ouro Branco","Congonhas","Carandaí","Outra cidade ou estado"] },
{ id:"q5", type:"checkbox", title:"Quantas pessoas você gostaria de compartilhar o Villa Rica?", helper:"Marque todas as opções desejadas.", options:["Somente eu","Com esposo(a)","Com os Filhos","Com os Pais","Com os irmãos","Outros familiares"] },
{ id:"q6", type:"radio", title:"Qual dessas experiências mais combina com você?", helper:"As atrações que você mais curte indicam o plano ideal.", options:["Piscinas aquecidas e área de descanso","Rio lento e momentos tranquilos","Academia e prática esportiva","Quadras e atividades com amigos","Todas as opções"] },
{ id:"q7", type:"radio", title:"Você pretende garantir algo assim para sua família em quanto tempo?", helper:"Serve para entender urgência.", options:["O quanto antes","Ainda este ano","Nos próximos 6 meses","Nos próximos 12 meses","Só estou pesquisando por enquanto"] } ];
const state = { step: 0, answers: {} };
const elBox = document.getElementById("vrqBox"); const elStepLabel = document.getElementById("vrqStepLabel"); const elBar = document.getElementById("vrqBar"); const elTitle = document.getElementById("vrqQuestionTitle"); const elOptions = document.getElementById("vrqOptions"); const elHelper = document.getElementById("vrqHelper"); const elPrev = document.getElementById("vrqPrevBtn"); const elNext = document.getElementById("vrqNextBtn");
function pct(){ return Math.round(((state.step + 1) / QUESTIONS.length) * 100); }
function setBoxAnimIn(){ elBox.classList.remove("vrq-anim-out"); elBox.classList.remove("vrq-anim"); void elBox.offsetWidth; elBox.classList.add("vrq-anim"); }
function setBoxAnimOut(){ elBox.classList.remove("vrq-anim"); elBox.classList.remove("vrq-anim-out"); void elBox.offsetWidth; elBox.classList.add("vrq-anim-out"); }
function escapeHtml(str){ return String(str) .replaceAll("&","&") .replaceAll("<","<") .replaceAll(">",">") .replaceAll('"',""") .replaceAll("'","'"); }
function isValidEmail(v){ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v || "").trim()); }
function phoneDigits(v){ return String(v || "").replace(/\D/g,""); }
function canProceed(){ const q = QUESTIONS[state.step]; const a = state.answers[q.id];
if(q.type === "text") return (a || "").trim().length >= 2; if(q.type === "tel") return phoneDigits(a).length >= 10; if(q.type === "email") return a === "__skip__" || a === "" || isValidEmail(a); if(q.type === "radio") return !!a; if(q.type === "checkbox") return Array.isArray(a) && a.length > 0;
return false; }
function updateNextBtn(){ const ok = canProceed(); elNext.textContent = (state.step === QUESTIONS.length - 1) ? "Finalizar" : "Continuar"; elNext.disabled = !ok; elNext.style.opacity = ok ? 1 : .70; }
let sentPartial = false; let sentFinal = false;
function buildPayload(stage){ const name = (state.answers.q1 || "").trim(); const phone = phoneDigits(state.answers.q2 || ""); const emailRaw = state.answers.q3; const email = (emailRaw === "__skip__") ? "Prefiro não informar" : (emailRaw || ""); const city = state.answers.q4 || ""; const share = Array.isArray(state.answers.q5) ? state.answers.q5.join(", ") : ""; const experience = state.answers.q6 || ""; const when = state.answers.q7 || "";
return { stage, name, phone, email, city, share, experience, when, page: (typeof location !== "undefined" ? location.href : ""), ua: (typeof navigator !== "undefined" ? navigator.userAgent : "") }; }
async function sendToSheets(stage){ if(!SHEETS_WEBAPP_URL) return;
const payload = buildPayload(stage); if(payload.phone.length < 10) return; try{ await fetch(SHEETS_WEBAPP_URL, { method: "POST", mode: "no-cors", headers: { "Content-Type": "text/plain;charset=utf-8" }, body: JSON.stringify(payload) }); }catch(e){} } function trySendPartial(){ if(sentPartial) return; const phone = phoneDigits(state.answers.q2 || ""); if(phone.length >= 10){ sentPartial = true; sendToSheets("parcial"); } }
function trySendFinal(){ if(sentFinal) return; sentFinal = true; sendToSheets("final"); }
function render(){ const q = QUESTIONS[state.step]; const total = String(QUESTIONS.length).padStart(2,"0"); const cur = String(state.step + 1).padStart(2,"0");
elStepLabel.textContent = "Pergunta " + cur + " de " + total; elBar.style.width = pct() + "%";
elTitle.textContent = q.title; elHelper.textContent = q.helper || ""; elOptions.innerHTML = "";
if(q.type === "text"){ elOptions.innerHTML = `
`; } else if(q.type === "tel"){ elOptions.innerHTML = `
`; } else if(q.type === "email"){ const current = state.answers[q.id] || ""; const skipChecked = current === "__skip__";
elOptions.innerHTML = `
`; } else if(q.type === "radio"){ const selected = state.answers[q.id] || ""; q.options.forEach((opt, idx) => { const rid = q.id + "_" + idx; elOptions.innerHTML += `
`; }); } else if(q.type === "checkbox"){ const arr = Array.isArray(state.answers[q.id]) ? state.answers[q.id] : []; q.options.forEach((opt, idx) => { const rid = q.id + "_" + idx; elOptions.innerHTML += `
`; }); }
elPrev.disabled = state.step === 0; elPrev.style.opacity = state.step === 0 ? .55 : 1;
updateNextBtn(); setBoxAnimIn(); }
function buildMessage(type){ const lines = []; lines.push("Olá! Quero conhecer o Villa Rica (Complexo de Lazer) e entender o plano ideal para minha família."); lines.push(""); lines.push("Minhas respostas:");
QUESTIONS.forEach((q, i) => { let a = state.answers[q.id];
if(q.type === "checkbox"){ a = Array.isArray(a) && a.length ? a.join(", ") : "-"; } else if(q.type === "email"){ if(a === "__skip__" || !a) a = "Prefiro não informar"; } else { a = a || "-"; }
lines.push("• " + (i+1) + "/" + QUESTIONS.length + ": " + q.title + " — " + a); });
lines.push(""); lines.push(type === "visita" ? "Quero agendar uma visita e ver as condições do Passaport Vitalício." : "Quero falar com um consultor e receber as condições especiais do Passaport Vitalício." );
return lines.join("\n"); }
function showFinal(){ trySendFinal();
const msgConsultor = buildMessage("consultor"); const msgVisita = buildMessage("visita");
const consultorLink = "https://wa.me/" + WHATS_NUMBER + "?text=" + encodeURIComponent(msgConsultor); const visitaLink = (VISIT_LINK_MODE === "url") ? VISIT_URL : ("https://wa.me/" + WHATS_NUMBER + "?text=" + encodeURIComponent(msgVisita));
const total = String(QUESTIONS.length).padStart(2,"0");
setBoxAnimOut(); setTimeout(() => { elBox.classList.remove("vrq-anim-out"); elBox.classList.remove("vrq-anim"); elBox.innerHTML = `
Pronto. Agora é o melhor passo.
Você está a poucos passos de garantir acesso ao Villa Rica – Complexo de Lazer.
Com base nas suas respostas, existe um plano ideal para você e sua família.
`; setBoxAnimIn(); }, 220); }
function goNext(){ if(!canProceed()) return;
const last = (state.step === QUESTIONS.length - 1);
setBoxAnimOut(); setTimeout(() => { if(last){ showFinal(); } else { state.step++; render(); } }, 220); }
function goPrev(){ if(state.step === 0) return;
setBoxAnimOut(); setTimeout(() => { state.step--; render(); }, 220); }
document.getElementById("vrqOptions").addEventListener("change", (e) => { const q = QUESTIONS[state.step]; const t = e.target; if(!t) return;
if(q.type === "checkbox"){ const arr = Array.isArray(state.answers[q.id]) ? state.answers[q.id] : []; if(t.checked){ if(!arr.includes(t.value)) arr.push(t.value); } else { const idx = arr.indexOf(t.value); if(idx >= 0) arr.splice(idx, 1); } state.answers[q.id] = arr;
updateNextBtn(); return; }
if(q.type === "email" && t.id === (q.id + "_skip")){ if(t.checked){ state.answers[q.id] = "__skip__"; updateNextBtn(); setTimeout(goNext, 160); } else { state.answers[q.id] = ""; updateNextBtn(); } return; }
if(q.type === "radio"){ state.answers[q.id] = t.value;
t.closest(".vrq-field")?.classList.add("vrq-picked"); setTimeout(() => t.closest(".vrq-field")?.classList.remove("vrq-picked"), 220);
updateNextBtn(); return; } });
document.getElementById("vrqOptions").addEventListener("input", (e) => { const q = QUESTIONS[state.step]; const t = e.target; if(!t || t.name !== q.id) return;
state.answers[q.id] = t.value;
if(q.id === "q2"){ trySendPartial(); }
updateNextBtn(); });
elNext.addEventListener("click", goNext); elPrev.addEventListener("click", goPrev);
render();
/* ====== INTRO VSL GATE ====== */ const VSL_URL = "https://complexovillarica.com/wp-content/uploads/2026/02/video2026.1.mp4"; const gate = document.getElementById("vslGate"); const vsl = document.getElementById("vslVideo"); const prog = document.getElementById("vslProg"); const timeEl = document.getElementById("vslTime"); const totalEl = document.getElementById("vslTotal"); const btnSkip = document.getElementById("vslSkip"); const btnSound = document.getElementById("vslSound");
let gateClosed = false;
function fmt(t){ if (!isFinite(t)) return "--:--"; t = Math.max(0, Math.floor(t)); const m = String(Math.floor(t/60)).padStart(2,"0"); const s = String(t%60).padStart(2,"0"); return m + ":" + s; }
function updateBar(){ const dur = vsl.duration || 0; const cur = vsl.currentTime || 0; const p = dur ? Math.min(100, Math.max(0, (cur/dur)*100)) : 0; prog.style.width = p + "%"; timeEl.textContent = fmt(cur); }
function stopVslHard(){ try{ vsl.pause(); }catch(e){} try{ vsl.currentTime = 0; }catch(e){} try{ vsl.removeEventListener("timeupdate", updateBar); vsl.removeEventListener("ended", closeGate); }catch(e){} }
function closeGate(){ if (gateClosed) return; gateClosed = true;
stopVslHard();
gate.classList.add("is-hidden"); setTimeout(() => { gate.style.display = "none"; window.scrollTo({ top: 0, left: 0, behavior: "auto" }); initReveals(); initCounter(); initObrasProgress(); initObrasVideoToggle(); }, 380); }
try{ const source = vsl.querySelector("source"); if (source) source.src = VSL_URL; vsl.load(); }catch(e){}
vsl.muted = true; vsl.playsInline = true;
vsl.addEventListener("loadedmetadata", () => { totalEl.textContent = fmt(vsl.duration); updateBar(); });
vsl.addEventListener("timeupdate", updateBar); vsl.addEventListener("ended", closeGate);
btnSkip.addEventListener("click", () => { closeGate(); });
btnSound.addEventListener("click", async () => { try{ vsl.muted = false; await vsl.play(); btnSound.textContent = "Som ativado"; btnSound.disabled = true; btnSound.style.opacity = 0.85; }catch(e){ vsl.muted = false; try{ await vsl.play(); }catch(_){} } });
const tryPlay = () => { if (gateClosed) return; vsl.play().catch(()=>{}); }; tryPlay(); document.addEventListener("click", () => tryPlay(), { once:true }); document.addEventListener("touchstart", () => tryPlay(), { once:true, passive:true });
/* ====== REVEALS ====== */ function initReveals(){ const items = Array.from(document.querySelectorAll("[data-reveal]")); if (!items.length) return;
if (!("IntersectionObserver" in window)){ items.forEach(el => el.classList.add("is-visible")); return; }
const obs = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting){ entry.target.classList.add("is-visible"); obs.unobserve(entry.target); } }); }, { root: null, rootMargin: "0px 0px -12% 0px", threshold: 0.12 });
items.forEach(el => obs.observe(el));
requestAnimationFrame(() => { items.forEach(el => { const r = el.getBoundingClientRect(); if (r.top < (window.innerHeight * 0.92)) el.classList.add("is-visible"); }); }); } document.querySelectorAll("[data-reveal]").forEach(el => el.classList.remove("is-visible"));
/* ====== OBRAS: progresso + pausa só no clique ====== */ function initObrasProgress(){ const section = document.querySelector("#obras"); const bar = document.querySelector("#obras .vrx-progressFill"); const text = document.getElementById("vrxProgressText"); if(!section || !bar || !text) return;
if (!("IntersectionObserver" in window)){ const target = parseInt(bar.getAttribute("data-progress")) || 0; bar.style.width = target + "%"; text.textContent = target + "%"; return; }
const observer = new IntersectionObserver((entries)=>{ entries.forEach(entry=>{ if(entry.isIntersecting){ const target = parseInt(bar.getAttribute("data-progress")) || 0; bar.style.width = target + "%";
let count = 0; const interval = setInterval(()=>{ count++; text.textContent = count + "%"; if(count >= target) clearInterval(interval); }, 15);
observer.disconnect(); } }); }, { threshold: 0.4 });
observer.observe(section); }
function initObrasVideoToggle(){ const obrasVideo = document.getElementById("obrasVideo"); if(!obrasVideo) return; obrasVideo.addEventListener("click", () => { if (obrasVideo.paused) obrasVideo.play().catch(()=>{}); else obrasVideo.pause(); }, { passive:true }); }
/* ====== COUNTER ====== */ function initCounter(){ const el = document.getElementById("vrxCounter"); if (!el) return;
const target = 1.5; const duration = 1300; const step = target / (duration / 16); let current = 0; let started = false;
const start = () => { if (started) return; started = true; const timer = setInterval(() => { current += step; if (current >= target){ current = target; clearInterval(timer); } el.textContent = current.toFixed(1).replace(".", ",") + "%"; }, 16); };
if (!("IntersectionObserver" in window)){ start(); return; }
const obs = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting){ start(); obs.unobserve(entry.target); } }); }, { threshold: 0.45 });
obs.observe(el); }
/* ====== FAQ ====== */ function closeAllFaq(){ document.querySelectorAll(".vrx-faqQ").forEach(q => q.classList.remove("open")); document.querySelectorAll(".vrx-faqA").forEach(a => a.classList.remove("open")); } document.querySelectorAll(".vrx-faqQ").forEach(btn => { btn.addEventListener("click", () => { const ans = btn.nextElementSibling; const isOpen = btn.classList.contains("open"); closeAllFaq(); if (!isOpen){ btn.classList.add("open"); ans.classList.add("open"); } }); });
/* ====== PERF: autoplay do background ====== */ const bgVideo = document.querySelector(".vrq-bg video"); if (bgVideo){ const tryPlayBg = () => bgVideo.play().catch(()=>{}); document.addEventListener("click", tryPlayBg, { once:true }); document.addEventListener("touchstart", tryPlayBg, { once:true, passive:true }); tryPlayBg(); }
/* ====== MODAL 360 + FIX scroll ====== */ (function improveKuulaModalAndScroll(){ const modal = document.getElementById("videoModal"); const closeModalBtn = document.getElementById("closeVideoModal"); const frameWrap = document.getElementById("videoFrameWrap"); const iframe = document.getElementById("kuulaModalIframe"); if(!modal || !iframe) return;
let lastY = 0;
function openModal(e){ if(e) e.preventDefault(); lastY = window.scrollY || document.documentElement.scrollTop || 0;
const ds = iframe.getAttribute("data-src"); if(ds && iframe.src !== ds) iframe.src = ds;
modal.classList.add("active"); modal.setAttribute("aria-hidden", "false"); }
function closeModal(){ modal.classList.remove("active"); modal.setAttribute("aria-hidden", "true"); iframe.src = "about:blank"; setTimeout(() => { window.scrollTo({ top: lastY, left: 0, behavior: "auto" }); }, 60); }
["open360Btn","open360Btn2","open360Btn3"].forEach(id => { const b = document.getElementById(id); if (b) b.addEventListener("click", openModal); });
if(closeModalBtn) closeModalBtn.addEventListener("click", (e) => { e.stopPropagation(); closeModal(); }); modal.addEventListener("click", closeModal); if(frameWrap) frameWrap.addEventListener("click", (e) => e.stopPropagation()); document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeModal(); });
// fullscreen exit scroll fix (Kuula inline também) let fsLastY = 0; const saveScroll = () => { fsLastY = window.scrollY || document.documentElement.scrollTop || 0; }; document.addEventListener("touchstart", saveScroll, { passive:true }); document.addEventListener("mousedown", saveScroll);
function onFsChange(){ const fsEl = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
if(!fsEl){ setTimeout(() => { window.scrollTo({ top: fsLastY, left: 0, behavior: "auto" }); }, 60); } } document.addEventListener("fullscreenchange", onFsChange); document.addEventListener("webkitfullscreenchange", onFsChange); document.addEventListener("mozfullscreenchange", onFsChange); document.addEventListener("MSFullscreenChange", onFsChange); })();
/* ====== PERF: vídeos só tocam quando estão visíveis ====== */ (function lazyPlayVideos(){ const vids = [ document.getElementById("obrasVideo"), document.querySelector(".vr-cota-video") ].filter(Boolean);
if(!vids.length) return; if(!("IntersectionObserver" in window)) return;
const obs = new IntersectionObserver((entries)=>{ entries.forEach(entry=>{ const v = entry.target; if(entry.isIntersecting){ v.play().catch(()=>{}); }else{ try{ v.pause(); }catch(e){} } }); }, { threshold: 0.25 });
vids.forEach(v=> obs.observe(v)); })();
/* ====== CARROSSEL 3 ====== */ (() => { const root = document.getElementById('vrxCarousel3'); if(!root) return;
const track = root.querySelector('[data-track]'); const slides = Array.from(root.querySelectorAll('[data-slide]')); const btnPrev = root.querySelector('[data-prev]'); const btnNext = root.querySelector('[data-next]'); const dotsWrap = root.querySelector('[data-dots]'); const progressBar = root.querySelector('[data-progress]');
let index = 0; let timer = null; let progressRAF = null; let autoplayEnabled = true;
const WPM = 165; const EXTRA_SECONDS = 2.5; const MIN_SECONDS = 7; const MAX_SECONDS = 18; const RESUME_AFTER_MS = 4500;
const dots = slides.map((_, i) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'vrx-dot' + (i === 0 ? ' is-active' : ''); b.setAttribute('aria-label', 'Ir para a seção ' + (i + 1)); b.addEventListener('click', () => { userInteracted(); goTo(i); }); dotsWrap.appendChild(b); return b; });
function clamp(n, a, b){ return Math.max(a, Math.min(b, n)); }
function countWords(el){ const text = el.innerText.replace(/\s+/g, ' ').replace(/›|‹/g, ' ').trim(); if(!text) return 0; return text.split(' ').filter(Boolean).length; }
function readingSecondsForSlide(i){ const words = countWords(slides[i]); const seconds = (words / WPM) * 60 + EXTRA_SECONDS; return clamp(seconds, MIN_SECONDS, MAX_SECONDS); }
function updateUI(){ const x = -index * 100; track.style.transform = `translate3d(${x}%,0,0)`; dots.forEach((d, i) => d.classList.toggle('is-active', i === index)); }
function stopTimers(){ if(timer) clearTimeout(timer); timer = null; if(progressRAF) cancelAnimationFrame(progressRAF); progressRAF = null; }
function startProgress(durationMs){ if(!progressBar) return; const start = performance.now(); progressBar.style.width = '0%';
const tick = (now) => { const t = clamp((now - start) / durationMs, 0, 1); progressBar.style.width = (t * 100) + '%'; if(t < 1) progressRAF = requestAnimationFrame(tick); }; progressRAF = requestAnimationFrame(tick); } function scheduleNext(){ stopTimers(); if(!autoplayEnabled) return; const seconds = readingSecondsForSlide(index); const durationMs = Math.round(seconds * 1000); startProgress(durationMs); timer = setTimeout(() => { goTo((index + 1) % slides.length, { fromAuto: true }); }, durationMs); }
function goTo(i, opts = {}){ index = (i + slides.length) % slides.length; updateUI(); if(opts.fromAuto !== true){ if(progressBar) progressBar.style.width = '0%'; } scheduleNext(); }
function userInteracted(){ autoplayEnabled = false; stopTimers(); clearTimeout(userInteracted._t); userInteracted._t = setTimeout(() => { autoplayEnabled = true; scheduleNext(); }, RESUME_AFTER_MS); }
btnPrev && btnPrev.addEventListener('click', () => { userInteracted(); goTo(index - 1); }); btnNext && btnNext.addEventListener('click', () => { userInteracted(); goTo(index + 1); });
let isDown = false; let startX = 0; let dx = 0; const getX = (e) => (e.touches ? e.touches[0].clientX : e.clientX);
function onDown(e){ isDown = true; startX = getX(e); dx = 0; userInteracted(); track.style.transition = 'none'; }
function onMove(e){ if(!isDown) return; const x = getX(e); dx = x - startX;
const width = root.clientWidth || 1; const offsetPct = (dx / width) * 100; const base = -index * 100; track.style.transform = `translate3d(${base + offsetPct}%,0,0)`; }
function onUp(){ if(!isDown) return; isDown = false;
track.style.transition = ''; const threshold = Math.min(90, Math.max(40, root.clientWidth * 0.12)); if(Math.abs(dx) > threshold){ goTo(dx < 0 ? index + 1 : index - 1); }else{ updateUI(); scheduleNext(); } } root.addEventListener('mousedown', onDown); window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp); root.addEventListener('touchstart', onDown, { passive:true }); root.addEventListener('touchmove', onMove, { passive:true }); root.addEventListener('touchend', onUp); root.addEventListener('keydown', (e) => { if(e.key === 'ArrowLeft'){ userInteracted(); goTo(index - 1); } if(e.key === 'ArrowRight'){ userInteracted(); goTo(index + 1); } }); root.tabIndex = 0;
updateUI(); scheduleNext(); })();
})();
/* ====== NA MÍDIA: carrossel ====== */ (function initMidiaCarousel5(){ const root = document.getElementById('midiaCarousel5'); if(!root) return;
const track = root.querySelector('[data-track]'); const slides = Array.from(root.querySelectorAll('[data-slide]')); const btnPrev = root.querySelector('[data-prev]'); const btnNext = root.querySelector('[data-next]'); const dotsWrap = root.querySelector('[data-dots]'); const progressBar = root.querySelector('[data-progress]');
if(!track || slides.length <= 1) return; let index = 0; let timer = null; let raf = null; let autoplayEnabled = true; const SECONDS = 9; const RESUME_AFTER_MS = 4500; const clamp = (n,a,b)=> Math.max(a, Math.min(b,n));
const dots = slides.map((_, i) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'vrx-dot' + (i === 0 ? ' is-active' : ''); b.setAttribute('aria-label', 'Ir para a matéria ' + (i + 1)); b.addEventListener('click', () => { userInteracted(); goTo(i); }); dotsWrap.appendChild(b); return b; });
function updateUI(){ track.style.transform = `translate3d(${-index * 100}%,0,0)`; dots.forEach((d,i)=> d.classList.toggle('is-active', i === index)); }
function stop(){ if(timer) clearTimeout(timer); timer = null; if(raf) cancelAnimationFrame(raf); raf = null; }
function startProgress(durationMs){ if(!progressBar) return; const start = performance.now(); progressBar.style.width = '0%';
const tick = (now) => { const t = clamp((now - start) / durationMs, 0, 1); progressBar.style.width = (t * 100) + '%'; if(t < 1) raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); } function schedule(){ stop(); if(!autoplayEnabled) return; const durationMs = Math.round(SECONDS * 1000); startProgress(durationMs); timer = setTimeout(() => { goTo((index + 1) % slides.length, { fromAuto:true }); }, durationMs); }
function goTo(i, extra = {}){ index = (i + slides.length) % slides.length; updateUI(); if(extra.fromAuto !== true && progressBar) progressBar.style.width = '0%'; schedule(); }
function userInteracted(){ autoplayEnabled = false; stop(); clearTimeout(userInteracted._t); userInteracted._t = setTimeout(() => { autoplayEnabled = true; schedule(); }, RESUME_AFTER_MS); }
btnPrev && btnPrev.addEventListener('click', () => { userInteracted(); goTo(index - 1); }); btnNext && btnNext.addEventListener('click', () => { userInteracted(); goTo(index + 1); });
let isDown = false, startX = 0, dx = 0; const getX = (e)=> (e.touches ? e.touches[0].clientX : e.clientX);
function onDown(e){ isDown = true; startX = getX(e); dx = 0; userInteracted(); track.style.transition = 'none'; } function onMove(e){ if(!isDown) return; dx = getX(e) - startX;
const width = root.clientWidth || 1; const offsetPct = (dx / width) * 100; const base = -index * 100; track.style.transform = `translate3d(${base + offsetPct}%,0,0)`; } function onUp(){ if(!isDown) return; isDown = false; track.style.transition = '';
const threshold = Math.min(90, Math.max(40, root.clientWidth * 0.12)); if(Math.abs(dx) > threshold){ goTo(dx < 0 ? index + 1 : index - 1); }else{ updateUI(); schedule(); } } root.addEventListener('mousedown', onDown); window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp); root.addEventListener('touchstart', onDown, { passive:true }); root.addEventListener('touchmove', onMove, { passive:true }); root.addEventListener('touchend', onUp); root.tabIndex = 0; root.addEventListener('keydown', (e) => { if(e.key === 'ArrowLeft'){ userInteracted(); goTo(index - 1); } if(e.key === 'ArrowRight'){ userInteracted(); goTo(index + 1); } });
updateUI();
schedule();
})();


