const inicioDiv = document.getElementById('inicio');
const saqueDiv = document.getElementById('saque');
const loginDiv = document.getElementById('login');
const bonusDiv = document.getElementById('bonus');
const historicoDiv = document.getElementById('historico');
function playAudio() {
unlockGlovoAudio();
var audio = document.getElementById("meuAudio");
if (!audio) return;
try {
audio.muted = false;
audio.currentTime = 0;
var playPromise = audio.play();
if (playPromise && playPromise.catch) playPromise.catch(function () {});
} catch (e) {}
}
var __glovoAudioUnlocked = false;
function unlockGlovoAudio() {
if (__glovoAudioUnlocked) return;
try {
if (window.GlovoVsl && typeof window.GlovoVsl.unlockMedia === "function") {
window.GlovoVsl.unlockMedia();
}
} catch (e) {}
var audio = document.getElementById("meuAudio");
if (!audio) return;
try {
audio.muted = true;
var p = audio.play();
if (p && p.then) {
p.then(function () {
audio.pause();
audio.currentTime = 0;
audio.muted = false;
__glovoAudioUnlocked = true;
}).catch(function () {});
} else {
audio.pause();
audio.currentTime = 0;
audio.muted = false;
__glovoAudioUnlocked = true;
}
} catch (e) {}
}
(function bindGlovoAudioUnlock() {
function isFormTarget(node) {
if (window.GlovoVsl && typeof window.GlovoVsl.isFormTarget === "function") {
return window.GlovoVsl.isFormTarget(node);
}
var el = node;
var hops = 0;
while (el && el !== document && hops < 6) {
var tag = (el.tagName || "").toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select" || tag === "label") return true;
if (el.classList && (el.classList.contains("float-field") || el.classList.contains("form-input"))) return true;
el = el.parentElement;
hops++;
}
return false;
}
function onGesture(ev) {
if (isFormTarget(ev && ev.target)) return;
document.removeEventListener("touchstart", onGesture, true);
document.removeEventListener("pointerdown", onGesture, true);
document.removeEventListener("click", onGesture, true);
// Não roubar o focus do e-mail — desbloqueia no próximo tick
setTimeout(unlockGlovoAudio, 0);
}
document.addEventListener("touchstart", onGesture, { capture: true, passive: true });
document.addEventListener("pointerdown", onGesture, { capture: true });
document.addEventListener("click", onGesture, true);
})();
function setCookie(cname, cvalue, exdays) {
try {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
const expires = `expires=${d.toUTCString()}`;
// encodeURIComponent — Safari/iOS rejeita cookies com "@" em claro
document.cookie =
String(cname) +
"=" +
encodeURIComponent(String(cvalue == null ? "" : cvalue)) +
"; " +
expires +
"; path=/; SameSite=Lax";
} catch (e) {}
}
function getCookie(cname) {
try {
var name = cname + "=";
var ca = String(document.cookie || "").split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === " ") c = c.substring(1);
if (c.indexOf(name) !== 0) continue;
var raw = c.substring(name.length);
try {
raw = decodeURIComponent(raw);
} catch (e) {}
if (
raw.length >= 2 &&
((raw.charAt(0) === '"' && raw.charAt(raw.length - 1) === '"') ||
(raw.charAt(0) === "'" && raw.charAt(raw.length - 1) === "'"))
) {
raw = raw.slice(1, -1);
}
return raw;
}
} catch (e) {}
return "";
}
let valor = parseFloat(getCookie('saldo'));
if (Number.isNaN(valor)) valor = 0;
const valorSpan = document.getElementById('valor');
const valorSpanSaque = document.getElementById('valor-saque');
const valorSpanMoney = document.getElementById('valor-money');
function formatEuro(n) {
return '€' + n.toLocaleString('pt-PT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function atualizarValor() {
if (valorSpan) valorSpan.textContent = formatEuro(valor);
if (valorSpanSaque) valorSpanSaque.textContent = formatEuro(valor);
if (valorSpanMoney) valorSpanMoney.textContent = formatEuro(valor);
setCookie('saldo', valor.toFixed(2), 365);
preencherQuantiaSaldo();
}
var __saldoAnimRaf = null;
var __saldoTickCtx = null;
function playSaldoTick() {
try {
if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
return;
}
var Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) return;
if (!__saldoTickCtx) __saldoTickCtx = new Ctx();
var ctx = __saldoTickCtx;
if (ctx.state === "suspended") {
ctx.resume().catch(function () {});
}
var now = ctx.currentTime;
function blip(freq, start, dur, peak) {
var o = ctx.createOscillator();
var g = ctx.createGain();
o.type = "triangle";
o.frequency.setValueAtTime(freq, start);
g.gain.setValueAtTime(0.0001, start);
g.gain.exponentialRampToValueAtTime(peak, start + 0.01);
g.gain.exponentialRampToValueAtTime(0.0001, start + dur);
o.connect(g);
g.connect(ctx.destination);
o.start(start);
o.stop(start + dur + 0.02);
}
blip(880, now, 0.08, 0.05);
blip(1320, now + 0.06, 0.1, 0.06);
blip(1760, now + 0.14, 0.12, 0.045);
} catch (e) {}
}
function animarSaldoDisplay(from, to, ms) {
ms = ms || 800;
if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
atualizarValor();
return;
}
if (__saldoAnimRaf) {
cancelAnimationFrame(__saldoAnimRaf);
__saldoAnimRaf = null;
}
var start = performance.now();
[valorSpan, valorSpanMoney, valorSpanSaque].forEach(function (el) {
if (el) el.classList.add("is-ticking");
});
function tick(now) {
var t = Math.min(1, (now - start) / ms);
var eased = 1 - Math.pow(1 - t, 3);
var cur = from + (to - from) * eased;
var txt = formatEuro(cur);
if (valorSpan) valorSpan.textContent = txt;
if (valorSpanSaque) valorSpanSaque.textContent = txt;
if (valorSpanMoney) valorSpanMoney.textContent = txt;
if (t < 1) {
__saldoAnimRaf = requestAnimationFrame(tick);
} else {
__saldoAnimRaf = null;
atualizarValor();
setTimeout(function () {
[valorSpan, valorSpanMoney, valorSpanSaque].forEach(function (el) {
if (el) el.classList.remove("is-ticking");
});
}, 200);
}
}
__saldoAnimRaf = requestAnimationFrame(tick);
}
let PREMIOS = [73.74, 84.19, 91.36, 97.82, 103.47, 88.65, 112.93, 106.28, 119.41, 122.15];
let valoresDesejados = PREMIOS.slice();
let etapaAtual = 1;
let surveyTotal = PREMIOS.length;
let cmsReady = false;
var CMS_FALLBACK_SURVEYS = [
{ title: "McDonald's", image: "images/mcdonalds-pt.jpg", prize: 94.37 },
{ title: "Burger King", image: "images/burguerking.jpg", prize: 88.64 },
{ title: "KFC", image: "images/kfc-pt.jpg", prize: 91.28 },
{ title: "Telepizza", image: "images/telepizza.jpg", prize: 58.73 },
{ title: "Pizza Hut", image: "images/pizzahut.jpg", prize: 59.45 },
{ title: "Nando's", image: "images/nandos.jpg", prize: 36.12 },
{ title: "Subway", image: "images/subway.jpg", prize: 82.91 },
];
function readCachedSurveys() {
try {
var raw = localStorage.getItem("glovo_cms_surveys_v2") || localStorage.getItem("glovo_cms_surveys");
if (!raw) return null;
var data = JSON.parse(raw);
if (Array.isArray(data) && data.length) return sanitizeSurveyImages(data);
} catch (e) {}
return null;
}
function writeCachedSurveys(surveys) {
try {
localStorage.setItem("glovo_cms_surveys_v2", JSON.stringify(surveys));
localStorage.removeItem("glovo_cms_surveys");
} catch (e) {}
}
/** Corrige paths .png antigos em cache → .jpg comprimidos (sem quebrar funil) */
function sanitizeSurveyImages(surveys) {
return surveys.map(function (s) {
if (!s || !s.image) return s;
var img = String(s.image);
if (/\.png(\?|$)/i.test(img)) {
img = img.replace(/\.png(\?|$)/i, ".jpg$1");
}
// upload istock em falta → mcdonalds-pt
if (img.indexOf("istockphoto") >= 0 || img.indexOf("images/uploads/") === 0 && img.indexOf("mcdonald") < 0) {
// only rewrite known-broken mcdonalds slot if title matches
if (String(s.title || "").toLowerCase().indexOf("mcdonald") >= 0) {
img = "images/mcdonalds-pt.jpg";
}
}
if (img === s.image) return s;
var copy = {};
for (var k in s) if (Object.prototype.hasOwnProperty.call(s, k)) copy[k] = s[k];
copy.image = img;
return copy;
});
}
function hideLoginBoot() {
var boot = document.getElementById("login-boot");
if (boot) boot.hidden = true;
}
/** UI imediata — nunca esperar /api/cms nem pixels */
function bootSurveyUiNow() {
if (!document.getElementById("ad1")) {
renderSurveys(readCachedSurveys() || CMS_FALLBACK_SURVEYS);
}
try {
bootSessao();
} catch (e) {
try {
mostrarPagina("inicio");
mostrarAd(1);
} catch (e2) {}
}
// Cinto de segurança: sessão com login escondido + início none = ecrã branco
try {
var authed = document.documentElement.classList.contains("glovo-authed");
var inicio = document.getElementById("inicio");
var login = document.getElementById("login");
var loginGone =
!login ||
login.style.display === "none" ||
getComputedStyle(login).display === "none";
var inicioGone =
!inicio ||
(inicio.style.display === "none" && getComputedStyle(inicio).display === "none");
if (authed && loginGone && inicioGone) {
mostrarPagina("inicio");
}
} catch (e3) {}
hideLoginBoot();
try {
document.documentElement.classList.add("glovo-ui-ready");
document.dispatchEvent(new Event("glovo:ui-ready"));
} catch (e4) {}
}
window.bootSurveyUiNow = bootSurveyUiNow;
function assetUrl(path) {
if (!path) return '';
if (/^https?:\/\//i.test(path) || path.indexOf('data:') === 0) return path;
return path.charAt(0) === '/' ? path : path;
}
function aplicarAssets(assets) {
if (!assets) return;
document.querySelectorAll('[data-cms]').forEach(function (el) {
var key = el.getAttribute('data-cms');
if (assets[key]) el.setAttribute('src', assetUrl(assets[key]));
});
if (assets.favicon) {
var icon = document.getElementById('site-favicon');
if (icon) icon.href = assetUrl(assets.favicon);
}
}
function renderSurveys(surveys) {
var mount = document.getElementById('surveys-mount');
if (!mount) return;
surveyTotal = surveys.length;
PREMIOS = surveys.map(function (s) { return Number(s.prize) || 0; });
valoresDesejados = PREMIOS.slice();
mount.innerHTML = surveys.map(function (s, i) {
var n = i + 1;
var prize = formatEuro(s.prize);
var title = String(s.title || 'Restaurante').replace(/' +
'
' +
'
' +
'
' +
'
' +
'
' +
'Avaliação' +
'' + n + ' de ' + surveyTotal + '' +
'
' +
'
' +
'
' +
'
Responde e ganha ' + prize + '
' +
'
Quantas estrelas dás ao ' + title + '?
' +
'
' +
'' +
'' +
'' +
'' +
'' +
'
' +
'
Toca nas estrelas para avaliar
' +
'
Foste bem atendido/a no ' + title + '?
' +
'
' +
'' +
'' +
'
' +
'
Recomendarias o ' + title + '?
' +
'
' +
'' +
'' +
'
' +
'' +
'' +
'
' +
'
' +
'
' +
'' +
''
);
}).join('');
}
function setStarRating(container, rating) {
if (!container) return;
var value = Number(rating) || 0;
container.querySelectorAll('.rating-button--star').forEach(function (b) {
var r = Number(b.getAttribute('data-rating')) || 0;
b.classList.toggle('active', r <= value && value > 0);
b.setAttribute('aria-checked', r === value ? 'true' : 'false');
});
container.classList.toggle('is-rated', value > 0);
container.classList.remove('is-invalid');
container.setAttribute('data-value', String(value || ''));
var hint = container.parentElement && container.parentElement.querySelector('[data-stars-hint]');
if (hint) {
hint.textContent = value
? (value === 1 ? '1 estrela' : value + ' estrelas')
: 'Toca nas estrelas para avaliar';
}
}
function scrollAvaliacaoTopo(suave) {
var opts = { top: 0, left: 0, behavior: suave === false ? 'auto' : 'smooth' };
try {
window.scrollTo(opts);
if (document.documentElement) {
document.documentElement.scrollTo(opts);
}
if (document.body) {
document.body.scrollTo(opts);
}
} catch (err) {
window.scrollTo(0, 0);
}
}
function enviarAvaliacao(n) {
var box = document.getElementById('ad' + n);
if (!box) return;
var incompleto = false;
var stars = box.querySelector('.rating-container--stars');
var starValue = Number(stars && stars.getAttribute('data-value')) || 0;
if (!stars || starValue < 1) {
if (stars) stars.classList.add('is-invalid');
incompleto = true;
}
box.querySelectorAll('.rating-container:not(.rating-container--stars)').forEach(function (grupo) {
var ok = Boolean(grupo.querySelector('.rating-button.active'));
grupo.classList.toggle('is-invalid', !ok);
if (!ok) incompleto = true;
});
if (incompleto) {
mostrarAviso('Faltam respostas', 'Escolhe as estrelas e responde às perguntas para enviar a avaliação.', 'Responder agora');
return;
}
if (window.reportVisit) window.reportVisit({ survey: n });
if (window.GlovoTrack && window.GlovoTrack.clarityFunnel) {
window.GlovoTrack.clarityFunnel("survey_" + n, { upgrade: n >= 5 ? "survey_mid" : false });
window.GlovoTrack.clarityTag("survey_last", String(n));
}
var btn = document.getElementById('B' + n);
var popup = document.getElementById('popupB' + n);
if (btn) btn.disabled = true;
if (popup) popup.style.display = 'block';
playAudio();
// Enquanto o popup está no ecrã, sobe suavemente para a imagem do restaurante
scrollAvaliacaoTopo(true);
setTimeout(function () {
if (popup) popup.style.display = 'none';
aumentarValor();
var next = n >= surveyTotal ? 'ad11' : 'ad' + (n + 1);
trocarDiv('ad' + n, next);
scrollAvaliacaoTopo(true);
}, 4000);
}
function chaveProgresso(email) {
return 'glovo_prog_' + String(email || '').trim().toLowerCase();
}
function paginaAtual() {
if (saqueDiv && saqueDiv.style.display === 'block') return 'saque';
if (bonusDiv && bonusDiv.style.display === 'block') return 'bonus';
if (historicoDiv && historicoDiv.style.display === 'block') return 'historico';
if (inicioDiv && inicioDiv.style.display === 'block') return 'inicio';
return 'login';
}
function guardarProgresso(pagina) {
var email = getCookie("email");
if (!email) {
try {
email = String(localStorage.getItem("glovo_email") || "")
.trim()
.toLowerCase();
} catch (e) {}
}
if (!email) return;
var data = {
etapa: etapaAtual,
saldo: Number(valor.toFixed(2)),
pagina: pagina || paginaAtual(),
updatedAt: Date.now(),
};
try {
localStorage.setItem(chaveProgresso(email), JSON.stringify(data));
} catch (e2) {}
setCookie("email", email, 365);
setCookie("saldo", valor.toFixed(2), 365);
setCookie("etapa", String(etapaAtual), 365);
}
function lerProgresso(email) {
try {
var raw = localStorage.getItem(chaveProgresso(email));
if (raw) {
var data = JSON.parse(raw);
if (data && typeof data === 'object') {
return {
etapa: parseInt(data.etapa, 10) || 1,
saldo: Number.isNaN(parseFloat(data.saldo)) ? 0 : parseFloat(data.saldo),
pagina: data.pagina || 'inicio'
};
}
}
} catch (e) {}
var etapaCookie = parseInt(getCookie('etapa'), 10);
var saldoCookie = parseFloat(getCookie('saldo'));
return {
etapa: Number.isNaN(etapaCookie) ? 1 : etapaCookie,
saldo: Number.isNaN(saldoCookie) ? 0 : saldoCookie,
pagina: 'inicio'
};
}
function actualizarBarra(n) {
if (n < 1 || n > surveyTotal) return;
var box = document.getElementById('ad' + n);
if (!box) return;
var count = box.querySelector('.survey__progress-count');
var fill = box.querySelector('.survey__progress-fill');
if (count) count.textContent = n + ' de ' + surveyTotal;
if (fill) fill.style.width = Math.round((n / surveyTotal) * 100) + '%';
}
function hydrateSurveyHero(n) {
var ad = document.getElementById('ad' + n);
if (!ad) return;
var img = ad.querySelector('.survey__hero img');
if (!img) return;
var pending = img.getAttribute('data-src');
if (pending) {
img.setAttribute('src', pending);
img.removeAttribute('data-src');
}
// Prefetch da próxima (só 1) para transição instantânea
var next = document.getElementById('ad' + (n + 1));
if (!next) return;
var nextImg = next.querySelector('.survey__hero img[data-src]');
if (!nextImg) return;
var nextSrc = nextImg.getAttribute('data-src');
if (!nextSrc) return;
var pre = new Image();
pre.decoding = 'async';
pre.src = nextSrc;
}
function mostrarAd(n) {
for (var i = 1; i <= surveyTotal; i++) {
var el = document.getElementById('ad' + i);
if (el) el.style.display = 'none';
}
var ad11 = document.getElementById('ad11');
if (ad11) ad11.style.display = 'none';
if (n >= 1 && n <= surveyTotal) {
var ad = document.getElementById('ad' + n);
if (ad) ad.style.display = 'block';
hydrateSurveyHero(n);
actualizarBarra(n);
}
}
function aplicarProgresso(state) {
var etapa = parseInt(state && state.etapa, 10);
if (Number.isNaN(etapa) || etapa < 1) etapa = 1;
var fim = surveyTotal + 1;
if (etapa > fim) etapa = fim;
etapaAtual = etapa;
var saldo = parseFloat(state && state.saldo);
valor = Number.isNaN(saldo) ? 0 : saldo;
var feitos = Math.min(Math.max(etapaAtual - 1, 0), surveyTotal);
valoresDesejados = PREMIOS.slice(feitos);
atualizarValor();
mostrarAd(etapaAtual);
var pagina = (state && state.pagina) || 'inicio';
if (pagina === 'login') pagina = 'inicio';
try {
var forced =
new URLSearchParams(window.location.search).get("pagina") ||
sessionStorage.getItem("glovo_landing_page") ||
"";
if (forced) {
try {
sessionStorage.removeItem("glovo_landing_page");
} catch (e2) {}
if (
forced === "saque" ||
forced === "bonus" ||
forced === "historico" ||
forced === "inicio"
) {
pagina = forced;
}
}
} catch (eForce) {}
mostrarPagina(
pagina === 'saque' || pagina === 'bonus' || pagina === 'historico' ? pagina : 'inicio'
);
if (etapaAtual > surveyTotal) verificarValor();
syncPaidFlagsFromServer(function () {
refreshFunnelDonePanel();
});
if (window.reportVisit && feitos >= 1) {
window.reportVisit({ survey: feitos });
}
}
function aumentarValor() {
if (valoresDesejados.length > 0) {
const valorIncremento = valoresDesejados.shift();
const from = valor;
valor += valorIncremento;
const to = valor;
setCookie('saldo', valor.toFixed(2), 365);
verificarValor();
guardarProgresso('inicio');
animarSaldoDisplay(from, to, 750 + Math.floor(Math.random() * 150));
playSaldoTick();
try {
if (navigator.vibrate) navigator.vibrate(30);
} catch (e) {}
}
}
function mostrarPagina(pagina) {
if (inicioDiv) inicioDiv.style.display = pagina === 'inicio' ? 'block' : 'none';
if (saqueDiv) saqueDiv.style.display = pagina === 'saque' ? 'block' : 'none';
if (loginDiv) loginDiv.style.display = pagina === 'login' ? 'flex' : 'none';
if (bonusDiv) bonusDiv.style.display = pagina === 'bonus' ? 'block' : 'none';
if (historicoDiv) historicoDiv.style.display = pagina === 'historico' ? 'block' : 'none';
document.querySelectorAll('.menuemb__item').forEach(function (item) {
item.classList.toggle('is-active', item.getAttribute('data-nav') === pagina);
});
if (pagina === 'saque') preencherQuantiaSaldo();
if (pagina === 'inicio') refreshFunnelDonePanel();
if (pagina === 'historico') renderHistorico();
if (pagina === 'saque' || pagina === 'inicio' || pagina === 'bonus' || pagina === 'historico') {
guardarProgresso(pagina);
}
}
function trocarDiv(esconderId, mostrarId) {
var hide = document.getElementById(esconderId);
var show = document.getElementById(mostrarId);
if (hide) hide.style.display = 'none';
// ad11 é só sentinela pós-avaliações — nunca mostrar caixa vazia
if (show && mostrarId !== 'ad11') show.style.display = 'block';
var match = String(mostrarId).match(/^ad(\d+)$/);
if (match) {
var num = parseInt(match[1], 10);
if (mostrarId === 'ad11' || num > surveyTotal) {
etapaAtual = surveyTotal + 1;
} else {
etapaAtual = num;
hydrateSurveyHero(num);
if (etapaAtual <= surveyTotal) actualizarBarra(etapaAtual);
}
guardarProgresso('inicio');
if (window.reportVisit && etapaAtual > 1) {
window.reportVisit({ survey: Math.min(Math.max(etapaAtual - 1, 0), surveyTotal) });
}
}
}
// Avaliações dinâmicas: enviarAvaliacao(n)
//---------------------------- Métodos de levantamento ---------------------------
let metodoAtivo = null;
let spinTipo = 'particular';
function selecionarMetodo(metodo) {
metodoAtivo = metodo;
document.querySelectorAll('.method-card').forEach(function (card) {
card.classList.toggle('active', card.getAttribute('data-method') === metodo);
});
document.querySelectorAll('.method-panel').forEach(function (panel) {
panel.classList.toggle('is-open', panel.id === 'panel-' + metodo);
});
var extra = document.getElementById('levantamento-extra');
if (extra) extra.style.display = 'block';
}
function selecionarSpinTipo(tipo) {
spinTipo = tipo;
var particular = document.getElementById('spin-particular');
var empresa = document.getElementById('spin-empresa');
var fieldP = document.getElementById('spin-field-particular');
var fieldE = document.getElementById('spin-field-empresa');
if (particular) particular.classList.toggle('active', tipo === 'particular');
if (empresa) empresa.classList.toggle('active', tipo === 'empresa');
if (fieldP) fieldP.style.display = tipo === 'particular' ? 'block' : 'none';
if (fieldE) fieldE.style.display = tipo === 'empresa' ? 'block' : 'none';
}
function toggleButton(buttonNumber) {
selecionarMetodo(['sepa', 'spin', 'mbway', 'paypal'][buttonNumber - 1]);
}
// Popup SAQUE
function formatUnlockEuro(n) {
return (
"€" +
Number(n).toLocaleString("pt-PT", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
);
}
function parsePayResumeState() {
var path = window.getPayResume ? window.getPayResume() : "/checkout.html";
if (/liberado/i.test(path)) return { kind: "done", path: path };
var m = String(path).match(/[?&]step=(\d+)/i);
if (/upsell/i.test(path) && m) {
return { kind: "upsell", step: parseInt(m[1], 10) || 1, path: path };
}
return { kind: "checkout", path: path };
}
function setUnlockListItem(li, icon, copy) {
if (!li) return;
li.innerHTML =
'' +
icon +
" " +
String(copy || "");
}
function applyUnlockPopupContent(fees) {
var resume = parsePayResumeState();
var kicker = document.querySelector(".unlock-popup__kicker");
var title = document.querySelector(".unlock-popup__title");
var text = document.querySelector(".unlock-popup__text");
var label = document.querySelector(".unlock-fee__label");
var value = document.getElementById("unlock-fee-value");
var note = document.querySelector(".unlock-fee__note");
var cta = document.querySelector(".unlock-popup__cta");
var items = document.querySelectorAll(".unlock-list li");
var upsells = (fees && fees.upsells) || [];
if (resume.kind === "upsell") {
var idx = Math.min(Math.max(resume.step, 1), Math.max(upsells.length, 1)) - 1;
var u = upsells[idx] || {};
var amt = Number(u.amount) || 0;
var total = upsells.length || 0;
var stepNo = idx + 1;
if (kicker) kicker.textContent = "Continua onde paraste";
if (title) title.textContent = u.headline || u.title || "Continua o levantamento";
if (text) {
text.textContent =
"Já pagaste a validação. Falta esta etapa" +
(u.title ? " (“" + u.title + "”)" : "") +
" para o saldo continuar a ser libertado.";
}
if (label) label.textContent = u.title || "Próxima etapa";
if (value && amt > 0) value.textContent = formatUnlockEuro(amt);
if (note) {
note.textContent =
(total ? "Etapa " + stepNo + " de " + total + " · " : "") +
"MB WAY";
}
if (cta) cta.textContent = "Continuar libertação";
setUnlockListItem(items[0], "bolt", "Retomas exactamente nesta etapa");
setUnlockListItem(items[1], "schedule", "O teu saldo continua reservado");
setUnlockListItem(items[2], "account_balance_wallet", "Pagas só o que falta para libertar");
return;
}
if (resume.kind === "done") {
if (kicker) kicker.textContent = "Quase lá";
if (title) title.textContent = "Levantamento em curso";
if (text) {
text.textContent =
"Já concluíste as taxas deste processo. Continua para ver o estado do teu levantamento.";
}
if (label) label.textContent = "Processo concluído";
if (value) value.textContent = "OK";
if (note) note.textContent = "Podes acompanhar a libertação do saldo";
if (cta) cta.textContent = "Ver libertação";
setUnlockListItem(items[0], "check_circle", "Validação e etapas já pagas");
setUnlockListItem(items[1], "schedule", "O saldo segue para a tua conta");
setUnlockListItem(items[2], "account_balance_wallet", "Método de levantamento guardado");
return;
}
var checkoutAmt = Number(fees && fees.checkout && fees.checkout.amount) || 0;
if (kicker) kicker.textContent = "Último passo";
if (title) title.textContent = "Liberta o teu saldo";
if (text) {
text.textContent =
"Para impedir contas falsas e robots, confirmamos que és tu o titular. É uma taxa única de validação — depois o valor fica liberado para levantamento.";
}
if (label) label.textContent = "Taxa única de validação";
if (value && checkoutAmt > 0) value.textContent = formatUnlockEuro(checkoutAmt);
if (note) note.textContent = "O teu saldo continua reservado · MB WAY";
if (cta) cta.textContent = "Validar e libertar saldo";
setUnlockListItem(items[0], "bolt", "Confirmação rápida e libertação do saldo");
setUnlockListItem(items[1], "schedule", "Reserva do valor activa nas próximas 24 horas");
setUnlockListItem(items[2], "account_balance_wallet", "Recebes no método que acabaste de escolher");
}
function stopUnlockVsl() {
var host = document.getElementById("unlock-vsl-player");
var wrap = document.getElementById("unlock-vsl");
var popup = document.getElementById("popup");
if (host) {
try {
host.querySelectorAll("video").forEach(function (v) {
try {
v.pause();
} catch (e) {}
});
} catch (e) {}
host.innerHTML = "";
host.style.width = "";
host.style.height = "";
host.style.aspectRatio = "";
}
if (wrap) wrap.hidden = true;
if (popup) {
popup.classList.remove("has-vsl");
popup.classList.remove("is-leaving");
}
}
/** Congela o VSL sem mexer na posição do popup (evitar salto cima/baixo). */
function freezeUnlockPopupForLeave() {
var popup = document.getElementById("popup");
var host = document.getElementById("unlock-vsl-player");
var overlay = document.getElementById("popup-overlay");
if (popup) popup.classList.add("is-leaving");
if (overlay) overlay.classList.add("is-leaving");
// Cobre tudo: o user não vê reflow do vídeo no unload
var veil = document.getElementById("unlock-leave-veil");
if (!veil) {
veil = document.createElement("div");
veil.id = "unlock-leave-veil";
veil.className = "unlock-leave-veil";
veil.innerHTML = "A abrir…";
document.body.appendChild(veil);
}
veil.hidden = false;
if (!host) return;
var hr = host.getBoundingClientRect();
if (hr.width && hr.height) {
host.style.width = Math.round(hr.width) + "px";
host.style.height = Math.round(hr.height) + "px";
host.style.aspectRatio = "auto";
host.style.flexShrink = "0";
}
var video = host.querySelector("video");
try {
if (video && video.videoWidth > 0 && video.videoHeight > 0) {
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0);
try {
video.pause();
} catch (e0) {}
var img = document.createElement("img");
img.src = canvas.toDataURL("image/jpeg", 0.72);
img.alt = "";
img.setAttribute("draggable", "false");
img.style.cssText =
"position:absolute;inset:0;width:100%;height:100%;object-fit:contain;object-position:center;background:#000;display:block;";
host.innerHTML = "";
host.appendChild(img);
return;
}
} catch (e1) {}
try {
host.querySelectorAll("video").forEach(function (v) {
try {
v.pause();
} catch (e2) {}
});
} catch (e3) {}
}
function mountUnlockVsl(cfg) {
var unlock = cfg && cfg.unlock;
var wrap = document.getElementById("unlock-vsl");
var host = document.getElementById("unlock-vsl-player");
var popup = document.getElementById("popup");
var title = document.querySelector("#popup .unlock-popup__title");
var text = document.querySelector("#popup .unlock-popup__text");
var cta = document.querySelector("#popup .unlock-popup__cta");
var resume = typeof parsePayResumeState === "function" ? parsePayResumeState() : { kind: "checkout" };
// Só no popup de validação inicial — não nos resumes de upsell
if (
resume.kind !== "checkout" ||
!unlock ||
!unlock.enabled ||
!unlock.url ||
typeof GlovoVsl === "undefined"
) {
stopUnlockVsl();
return;
}
if (wrap) wrap.hidden = false;
if (popup) popup.classList.add("has-vsl");
if (title && unlock.headline) title.textContent = unlock.headline;
if (text && unlock.sub) text.textContent = unlock.sub;
if (cta && unlock.cta) cta.textContent = unlock.cta;
if (GlovoVsl.preloadUrl) GlovoVsl.preloadUrl(unlock.url);
GlovoVsl.mountPlayer(host, unlock.url);
}
function showPopup() {
function openUi() {
var overlay = document.getElementById("popup-overlay");
var popup = document.getElementById("popup");
if (overlay) overlay.classList.add("is-open");
if (popup) popup.classList.add("is-open");
if (window.GlovoTrack && window.GlovoTrack.clarityFunnel) {
window.GlovoTrack.clarityFunnel("unlock_popup", { upgrade: "unlock_popup" });
}
}
var paint = function (fees) {
window.__feesCache = fees || window.__feesCache || null;
applyUnlockPopupContent(window.__feesCache || {});
openUi();
var applyVsl = function (cfg) {
window.__vslCache = cfg || null;
mountUnlockVsl(cfg);
};
if (window.__vslCache) {
applyVsl(window.__vslCache);
return;
}
if (typeof GlovoVsl !== "undefined") {
GlovoVsl.load().then(applyVsl).catch(function () {
stopUnlockVsl();
});
}
};
if (window.__feesCache) {
paint(window.__feesCache);
return;
}
fetch("/api/fees", { cache: "no-store" })
.then(function (r) {
return r.json();
})
.then(paint)
.catch(function () {
paint({});
});
}
function closePopup() {
stopUnlockVsl();
var overlay = document.getElementById("popup-overlay");
var popup = document.getElementById("popup");
var veil = document.getElementById("unlock-leave-veil");
if (overlay) {
overlay.classList.remove("is-open");
overlay.classList.remove("is-leaving");
}
if (popup) {
popup.classList.remove("is-open");
popup.classList.remove("is-leaving");
}
if (veil) veil.hidden = true;
}
function goToPayResumeSafe() {
var btn = document.querySelector("#popup .unlock-popup__cta");
if (btn && btn.dataset.leaving === "1") return;
if (btn) {
btn.dataset.leaving = "1";
btn.disabled = true;
btn.textContent = "A abrir…";
}
freezeUnlockPopupForLeave();
var go = function () {
try {
if (typeof window.goToPayResume === "function") {
window.goToPayResume();
return;
}
} catch (e) {}
window.location.href = "/checkout.html";
};
// 1 frame para pintar o véu; sem reposicionar o popup
requestAnimationFrame(go);
}
// Popup LIMITE DIÁRIO / CONCLUSÃO DO FUNIL
function lsGetSafe(key) {
try {
return localStorage.getItem(key) || "";
} catch (e) {
return "";
}
}
function lsSetSafe(key, value) {
try {
localStorage.setItem(key, value);
} catch (e) {}
}
function isFunnelDone() {
return lsGetSafe("glovo_funnel_done") === "1";
}
function hasExpressPaidClient() {
return lsGetSafe("glovo_express_paid") === "1";
}
function hasVitalicioPaidClient() {
return lsGetSafe("glovo_vitalicio_paid") === "1";
}
function getReevalUntil() {
var n = parseInt(lsGetSafe("glovo_reeval_until"), 10);
return Number.isFinite(n) ? n : 0;
}
function deliveryPrazoText() {
if (hasExpressPaidClient()) {
return "O teu valor cairá em até 24 horas.";
}
return "O teu valor cairá em até 5 dias.";
}
function formatCountdown(ms) {
var total = Math.max(0, Math.floor(ms / 1000));
var h = Math.floor(total / 3600);
var m = Math.floor((total % 3600) / 60);
var s = total % 60;
function pad(n) {
return (n < 10 ? "0" : "") + n;
}
return pad(h) + ":" + pad(m) + ":" + pad(s);
}
function countdownParts(ms) {
var total = Math.max(0, Math.floor(ms / 1000));
return {
hours: Math.floor(total / 3600),
minutes: Math.floor((total % 3600) / 60),
seconds: total % 60,
};
}
function pad2(n) {
n = Math.max(0, Math.floor(n));
return (n < 10 ? "0" : "") + n;
}
function setFlipUnitValue(unitEl, value, animate) {
if (!unitEl) return;
var next = pad2(value);
var prev = unitEl.getAttribute("data-value");
var card = unitEl.querySelector(".flip-card");
var staticTop = unitEl.querySelector(".flip-card__static-top span");
var staticBottom = unitEl.querySelector(".flip-card__static-bottom span");
var flapTop = unitEl.querySelector(".flip-card__flap--top span");
var flapBottom = unitEl.querySelector(".flip-card__flap--bottom span");
if (!card || !staticTop || !staticBottom) return;
if (prev === null) {
unitEl.setAttribute("data-value", next);
staticTop.textContent = next;
staticBottom.textContent = next;
if (flapTop) flapTop.textContent = next;
if (flapBottom) flapBottom.textContent = next;
return;
}
if (prev === next) return;
if (!animate || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
unitEl.setAttribute("data-value", next);
staticTop.textContent = next;
staticBottom.textContent = next;
if (flapTop) flapTop.textContent = next;
if (flapBottom) flapBottom.textContent = next;
card.classList.remove("is-flipping");
return;
}
if (flapTop) flapTop.textContent = prev;
if (flapBottom) flapBottom.textContent = next;
staticTop.textContent = next;
staticBottom.textContent = prev;
card.classList.remove("is-flipping");
void card.offsetWidth;
card.classList.add("is-flipping");
clearTimeout(unitEl._flipTimer);
unitEl._flipTimer = setTimeout(function () {
staticBottom.textContent = next;
unitEl.setAttribute("data-value", next);
card.classList.remove("is-flipping");
}, 460);
}
function updateFlipClock(ms, animate) {
var parts = countdownParts(ms);
var root = document.getElementById("flip-clock");
if (!root) return;
setFlipUnitValue(root.querySelector('[data-unit="hours"]'), parts.hours, animate);
setFlipUnitValue(root.querySelector('[data-unit="minutes"]'), parts.minutes, animate);
setFlipUnitValue(root.querySelector('[data-unit="seconds"]'), parts.seconds, animate);
}
var __reevalTimerId = null;
var __flipClockReady = false;
function applyLimitPopupContent() {
var kicker = document.getElementById("popupL-kicker");
var congrats = document.getElementById("popupL-congrats");
var text = document.getElementById("popupL-text");
var expect = document.getElementById("popupL-expect");
var cta = document.getElementById("popupL-cta");
var note = document.getElementById("popupL-note");
var done = isFunnelDone();
var reevalRound = lsGetSafe("glovo_reeval_round") === "1";
if (done && !reevalRound) {
if (kicker) kicker.textContent = "Concluíste todas as etapas";
if (congrats) congrats.textContent = "Tudo certo!";
if (text) text.innerHTML = "O teu levantamento
está em processamento";
if (expect) expect.textContent = deliveryPrazoText() + " Reserva activa enquanto o valor não cai na conta.";
if (note) note.textContent = "Já está no teu saldo";
if (cta) {
cta.textContent = "Ver histórico";
cta.setAttribute("onclick", "fecharConclusaoFunil()");
}
return;
}
if (done && reevalRound) {
if (kicker) kicker.textContent = "Nova avaliação concluída";
if (congrats) congrats.textContent = "Parabéns!";
if (text) text.innerHTML = "O valor foi adicionado
ao teu saldo";
if (expect) {
expect.textContent =
"Avaliaste outras empresas. " + deliveryPrazoText();
}
if (note) note.textContent = "Saldo actualizado";
if (cta) {
cta.textContent = "Ver saldo";
cta.setAttribute("onclick", "irParaSaque()");
}
return;
}
if (kicker) kicker.textContent = "Limite diário atingido";
if (congrats) congrats.textContent = "Parabéns!";
if (text) text.innerHTML = "O teu saldo está
pronto a levantar";
if (expect) {
expect.textContent =
"Falta só a validação do titular para libertar o valor. Reserva activa por 24 horas.";
}
if (note) note.textContent = "Já está no teu saldo";
if (cta) {
cta.textContent = "Continuar para o levantamento";
cta.setAttribute("onclick", "irParaSaque()");
}
}
function showPopupL() {
applyLimitPopupContent();
if (isFunnelDone() && lsGetSafe("glovo_reeval_round") !== "1") {
if (lsGetSafe("glovo_done_popup_seen") === "1") {
refreshFunnelDonePanel();
return;
}
lsSetSafe("glovo_done_popup_seen", "1");
}
var popup = document.getElementById("popupL");
var overlay = document.getElementById("limit-overlay");
if (popup) {
popup.style.display = "block";
popup.classList.add("is-celebrating");
}
if (overlay) {
overlay.classList.add("is-open");
overlay.setAttribute("aria-hidden", "false");
}
var ring = document.getElementById("minha-barra-progresso");
if (ring) {
ring.style.transition = "none";
ring.setAttribute("stroke-dasharray", "0 100");
void ring.getBoundingClientRect();
ring.style.transition = "stroke-dasharray 1.35s cubic-bezier(.2,.8,.2,1)";
ring.setAttribute("stroke-dasharray", "100 100");
}
playAudio();
celebrarLimite();
}
function closePopupL() {
var popup = document.getElementById("popupL");
var overlay = document.getElementById("limit-overlay");
if (popup) {
popup.style.display = "none";
popup.classList.remove("is-celebrating");
}
if (overlay) {
overlay.classList.remove("is-open");
overlay.setAttribute("aria-hidden", "true");
}
var ring = document.getElementById("minha-barra-progresso");
if (ring) {
ring.style.transition = "none";
ring.setAttribute("stroke-dasharray", "0 100");
}
}
function fecharConclusaoFunil() {
closePopupL();
refreshFunnelDonePanel();
mostrarPagina("historico");
}
function irParaSaque() {
closePopupL();
rememberPendingWithdraw(valor);
if (window.GlovoTrack && window.GlovoTrack.clarityFunnel) {
window.GlovoTrack.clarityFunnel("go_saque", { upgrade: "go_saque" });
}
mostrarPagina("saque");
}
function setSurveysLocked(locked) {
var mount = document.getElementById("surveys-mount");
if (!mount) return;
mount.style.display = locked ? "none" : "";
for (var i = 1; i <= surveyTotal; i++) {
var ad = document.getElementById("ad" + i);
if (ad && locked) ad.style.display = "none";
}
var ad11 = document.getElementById("ad11");
if (ad11 && locked) ad11.style.display = "none";
}
function surveysCompleted() {
return surveyTotal > 0 && etapaAtual > surveyTotal;
}
function refreshPendingWithdrawPanel() {
var pending = document.getElementById("pending-withdraw-panel");
if (!pending) return false;
var show =
!isFunnelDone() &&
surveysCompleted() &&
lsGetSafe("glovo_reeval_round") !== "1";
pending.hidden = !show;
if (show) {
var bal = document.getElementById("pending-withdraw-balance");
if (bal) {
bal.textContent =
"Tens " + formatEuro(valor) + " no saldo, reservados para levantamento.";
}
setSurveysLocked(true);
}
return show;
}
function rememberPendingWithdraw(amount, method) {
var n = Number(amount);
if (!(n > 0)) n = Number(valor) || 0;
if (!(n > 0)) return;
lsSetSafe("glovo_pending_amount", String(n.toFixed(2)));
lsSetSafe("glovo_pending_at", String(Date.now()));
if (method) lsSetSafe("glovo_pending_method", String(method));
}
function getWithdrawals() {
try {
var raw = localStorage.getItem("glovo_withdrawals");
var list = raw ? JSON.parse(raw) : [];
return Array.isArray(list) ? list : [];
} catch (e) {
return [];
}
}
function saveWithdrawals(list) {
try {
localStorage.setItem("glovo_withdrawals", JSON.stringify(list || []));
} catch (e) {}
}
/** Junta levantamentos "Em processamento" duplicados (mesmo valor). */
function dedupeWithdrawals(list) {
if (!Array.isArray(list) || list.length < 2) return list || [];
var completed = [];
var openMap = {};
list.forEach(function (w) {
if (!w || typeof w !== "object") return;
if (String(w.status || "processing") === "completed") {
completed.push(w);
return;
}
var key = String(Math.round((Number(w.amount) || 0) * 100) / 100);
var prev = openMap[key];
if (!prev) {
openMap[key] = Object.assign({}, w);
return;
}
var a = openMap[key];
var aTs = Number(a.createdAt) || Number.MAX_SAFE_INTEGER;
var bTs = Number(w.createdAt) || Number.MAX_SAFE_INTEGER;
if (bTs < aTs) {
a.createdAt = w.createdAt;
if (w.id) a.id = w.id;
if (w.funnelDoneAt) a.funnelDoneAt = w.funnelDoneAt;
}
a.express = Boolean(a.express) || Boolean(w.express);
if (!a.method && w.method) a.method = w.method;
if (!a.funnelDoneAt && w.funnelDoneAt) a.funnelDoneAt = w.funnelDoneAt;
});
var open = Object.keys(openMap).map(function (k) {
return openMap[k];
});
open.sort(function (a, b) {
return (Number(b.createdAt) || 0) - (Number(a.createdAt) || 0);
});
return open.concat(completed);
}
function findOpenWithdrawal(list, doneAt, amount) {
if (!Array.isArray(list) || !list.length) return null;
var byDone = list.find(function (w) {
return (
w &&
String(w.status || "processing") !== "completed" &&
(Number(w.funnelDoneAt) === Number(doneAt) || w.id === "wd_" + doneAt)
);
});
if (byDone) return byDone;
var amt = Math.round((Number(amount) || 0) * 100) / 100;
if (amt > 0) {
var byAmt = list.find(function (w) {
return (
w &&
String(w.status || "processing") !== "completed" &&
Math.round((Number(w.amount) || 0) * 100) / 100 === amt
);
});
if (byAmt) return byAmt;
}
return (
list.find(function (w) {
return w && String(w.status || "processing") !== "completed";
}) || null
);
}
function ensureWithdrawHistory() {
if (!isFunnelDone()) return null;
var doneAt = getFunnelDoneAt() || Date.now();
var list = dedupeWithdrawals(getWithdrawals());
var amount =
parseFloat(lsGetSafe("glovo_pending_amount")) ||
parseFloat(lsGetSafe("glovo_last_withdraw_amount")) ||
0;
if (!(amount > 0)) {
amount = parseFloat(getCookie("saldo")) || 0;
}
var existing = findOpenWithdrawal(list, doneAt, amount);
if (existing) {
existing.express = Boolean(existing.express) || hasExpressPaidClient();
if (!existing.funnelDoneAt) existing.funnelDoneAt = doneAt;
if (!existing.method) existing.method = lsGetSafe("glovo_pending_method") || "";
if (!(Number(existing.amount) > 0) && amount > 0) {
existing.amount = Math.round(amount * 100) / 100;
}
saveWithdrawals(list);
try {
localStorage.removeItem("glovo_pending_amount");
} catch (e) {}
return existing;
}
if (!(amount > 0) && list.length) {
saveWithdrawals(list);
return list[0];
}
if (!(amount > 0)) {
saveWithdrawals(list);
return null;
}
var entry = {
id: "wd_" + doneAt,
amount: Math.round(amount * 100) / 100,
createdAt: doneAt,
funnelDoneAt: doneAt,
express: hasExpressPaidClient(),
method: lsGetSafe("glovo_pending_method") || "",
status: "processing",
};
list.unshift(entry);
saveWithdrawals(list);
lsSetSafe("glovo_last_withdraw_amount", String(entry.amount));
try {
localStorage.removeItem("glovo_pending_amount");
} catch (e) {}
return entry;
}
function isWithdrawInProgress() {
if (isFunnelDone()) return false;
if (lsGetSafe("glovo_checkout_paid") === "1") return true;
if (typeof window.hasPaidCheckout === "function" && window.hasPaidCheckout()) return true;
var resume = window.getPayResume ? String(window.getPayResume()) : "";
if (/upsell\.html/i.test(resume)) return true;
if (surveysCompleted()) return true;
return false;
}
function formatHistDate(ts) {
try {
return new Date(ts).toLocaleString("pt-PT", {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
} catch (e) {
return "";
}
}
function continuarLevantamento() {
if (isFunnelDone()) {
mostrarPagina("inicio");
return;
}
var resume = window.getPayResume ? String(window.getPayResume()) : "";
var checkoutPaid =
lsGetSafe("glovo_checkout_paid") === "1" ||
(typeof window.hasPaidCheckout === "function" && window.hasPaidCheckout());
if (checkoutPaid || /upsell\.html/i.test(resume)) {
if (window.goToPayResume) window.goToPayResume();
else window.location.href = resume || "/checkout.html";
return;
}
if (surveysCompleted()) {
mostrarPagina("saque");
return;
}
mostrarPagina("inicio");
}
function renderHistorico() {
ensureWithdrawHistory();
var empty = document.getElementById("hist-empty");
var progress = document.getElementById("hist-progress");
var listEl = document.getElementById("hist-list");
if (!empty || !progress || !listEl) return;
var list = getWithdrawals();
var inProgress = isWithdrawInProgress();
empty.hidden = true;
progress.hidden = true;
listEl.hidden = true;
listEl.innerHTML = "";
if (inProgress) {
progress.hidden = false;
var title = document.getElementById("hist-progress-title");
var text = document.getElementById("hist-progress-text");
var feeBox = document.getElementById("hist-progress-fee");
var feeLabel = document.getElementById("hist-progress-fee-label");
var feeValue = document.getElementById("hist-progress-fee-value");
var cta = document.getElementById("hist-progress-cta");
var resume = window.getPayResume ? String(window.getPayResume()) : "";
var checkoutPaid =
lsGetSafe("glovo_checkout_paid") === "1" ||
(typeof window.hasPaidCheckout === "function" && window.hasPaidCheckout());
if (checkoutPaid || /upsell\.html/i.test(resume)) {
if (title) title.textContent = "Conclui o teu levantamento";
if (text) {
text.textContent =
"Já começaste o processo. Continua nas taxas em falta para libertar o valor para a tua conta.";
}
if (cta) cta.textContent = "Continuar onde parei";
if (feeBox) feeBox.hidden = true;
fetch("/api/fees", { cache: "no-store" })
.then(function (r) {
return r.json();
})
.then(function (fees) {
var stepMatch = resume.match(/[?&]step=(\d+)/i);
var step = stepMatch ? parseInt(stepMatch[1], 10) : 0;
var upsells = (fees && fees.upsells) || [];
var fee = null;
var label = "Próxima etapa";
if (/checkout/i.test(resume) || (!step && !checkoutPaid)) {
fee = fees && fees.checkout;
label = (fee && fee.title) || "Taxa de validação";
} else if (step >= 1 && upsells[step - 1]) {
fee = upsells[step - 1];
label = (fee && fee.title) || "Taxa da etapa " + step;
} else if (checkoutPaid && upsells[0]) {
fee = upsells[0];
label = fee.title || "Próxima taxa";
}
if (fee && feeBox && feeLabel && feeValue) {
feeBox.hidden = false;
feeLabel.textContent = label;
feeValue.textContent = formatEuro(Number(fee.amount) || 0);
}
})
.catch(function () {});
} else {
if (title) title.textContent = "Saldo pronto a levantar";
if (text) {
text.textContent =
"Já concluíste as avaliações. Escolhe o método de recebimento e continua o levantamento para libertar o saldo.";
}
if (cta) cta.textContent = "Ir para o saldo";
if (feeBox) feeBox.hidden = true;
var pendingAmt = parseFloat(lsGetSafe("glovo_pending_amount")) || valor;
if (pendingAmt > 0 && feeBox && feeLabel && feeValue) {
feeBox.hidden = false;
feeLabel.textContent = "Valor a levantar";
feeValue.textContent = formatEuro(pendingAmt);
}
}
}
if (list.length) {
listEl.hidden = false;
listEl.innerHTML = list
.map(function (w) {
var express = Boolean(w.express);
var eta = express
? "Estimativa: até 24 horas"
: "Estimativa: até 5 dias úteis";
var badge = w.status === "completed" ? "Concluído" : "Em processamento";
var badgeClass = w.status === "completed" ? " is-done" : "";
return (
'' +
'' +
"
" +
'
' +
formatEuro(Number(w.amount) || 0) +
"
" +
'
' +
formatHistDate(w.createdAt || Date.now()) +
"
" +
"
" +
'
' +
badge +
"" +
"
" +
'Valor solicitado para levantamento' +
(w.method ? " · " + String(w.method).toUpperCase() : "") +
"
" +
'' +
eta +
"
" +
""
);
})
.join("");
}
if (!list.length && !inProgress) {
empty.hidden = false;
}
}
function syncWalletAfterRedeem() {
var wallet = document.getElementById("header-wallet");
if (wallet) wallet.classList.remove("is-hidden");
// Depois do funil, o valor já foi "resgatado" — carteira fica a €0,00 (visível).
if (isFunnelDone() && lsGetSafe("glovo_reeval_round") !== "1") {
if (valor > 0 && !lsGetSafe("glovo_pending_amount")) {
rememberPendingWithdraw(valor);
}
ensureWithdrawHistory();
if (valor !== 0) {
valor = 0;
setCookie("saldo", "0.00", 365);
try {
var email = getCookie("email");
if (email) guardarProgresso(paginaAtual() === "login" ? "inicio" : paginaAtual());
} catch (e) {}
}
if (valorSpan) valorSpan.textContent = formatEuro(0);
if (valorSpanMoney) valorSpanMoney.textContent = formatEuro(0);
preencherQuantiaSaldo();
return;
}
atualizarValor();
}
function getFunnelDoneAt() {
var n = parseInt(lsGetSafe("glovo_funnel_done_at"), 10);
return Number.isFinite(n) && n > 0 ? n : 0;
}
function ensureReevalUntilFromPayment(finalPaidAt) {
var REEVAL_MS = 24 * 60 * 60 * 1000;
var origin = lsGetSafe("glovo_reeval_origin");
// Depois de uma reavaliação, o cooldown seguinte começa nessa altura — não sobrescrever.
if (origin === "reeval") return getReevalUntil();
var doneAt = getFunnelDoneAt();
var paidAt = Number(finalPaidAt) > 0 ? Number(finalPaidAt) : 0;
// Identidade do levantamento = primeira conclusão; não reescrever em compras tardias.
if (!(doneAt > 0) && paidAt > 0) {
lsSetSafe("glovo_funnel_done_at", String(paidAt));
doneAt = paidAt;
}
if (!(doneAt > 0)) return getReevalUntil();
var cooldownBase = paidAt > 0 ? paidAt : doneAt;
var until = cooldownBase + REEVAL_MS;
lsSetSafe("glovo_reeval_until", String(until));
lsSetSafe("glovo_reeval_origin", "final");
return until;
}
function syncPaidFlagsFromServer(done) {
var id =
typeof window.getVisitorId === "function" ? window.getVisitorId() : lsGetSafe("glovo_vid");
if (!id) {
if (done) done();
return;
}
fetch("/api/visitor/flags?id=" + encodeURIComponent(id), { cache: "no-store" })
.then(function (r) {
return r.json();
})
.then(function (data) {
if (!data || data.error) return;
if (data.expressPaid) lsSetSafe("glovo_express_paid", "1");
if (data.vitalicioPaid) {
lsSetSafe("glovo_vitalicio_paid", "1");
}
if (data.finalPaidAt) {
lsSetSafe("glovo_funnel_done", "1");
if (!getFunnelDoneAt()) lsSetSafe("glovo_funnel_done_at", String(data.finalPaidAt));
ensureWithdrawHistory();
}
if (data.vitalicioPaid && (data.finalPaidAt || getFunnelDoneAt())) {
ensureReevalUntilFromPayment(data.finalPaidAt || getFunnelDoneAt());
}
})
.catch(function () {})
.then(function () {
if (done) done();
});
}
function refreshFunnelDonePanel() {
var panel = document.getElementById("funnel-done-panel");
if (!panel) return;
var delivery = document.getElementById("funnel-done-delivery");
var timerWrap = document.getElementById("funnel-done-timer-wrap");
var msg = document.getElementById("funnel-done-reeval-msg");
var startBtn = document.getElementById("funnel-done-start-btn");
var title = document.getElementById("funnel-done-title");
if (__reevalTimerId) {
clearInterval(__reevalTimerId);
__reevalTimerId = null;
}
__flipClockReady = false;
syncWalletAfterRedeem();
// Avaliações feitas, mas ainda não pagou o funil → painel de levantamento
if (!isFunnelDone()) {
panel.hidden = true;
if (timerWrap) timerWrap.hidden = true;
if (startBtn) startBtn.hidden = true;
if (msg) msg.hidden = true;
if (refreshPendingWithdrawPanel()) return;
setSurveysLocked(false);
return;
}
var pending = document.getElementById("pending-withdraw-panel");
if (pending) pending.hidden = true;
if (lsGetSafe("glovo_reeval_round") === "1") {
panel.hidden = true;
setSurveysLocked(false);
return;
}
panel.hidden = false;
setSurveysLocked(true);
if (title) title.textContent = "Concluíste todas as etapas";
if (delivery) delivery.textContent = deliveryPrazoText();
var vital = hasVitalicioPaidClient();
var until = getReevalUntil();
refreshLateOffers();
if (!vital) {
if (timerWrap) timerWrap.hidden = true;
if (startBtn) startBtn.hidden = true;
if (msg) {
msg.hidden = false;
msg.textContent =
"Sem o acesso vitalício, este processo serve só para este levantamento. Ainda tens tempo para activar o plano e continuares a avaliar todos os dias.";
}
return;
}
function setCtaReady(ready) {
if (!startBtn) return;
startBtn.hidden = false;
startBtn.textContent = "Fazer nova avaliação";
startBtn.classList.toggle("is-ready", ready);
}
function tick(animate) {
var left = until - Date.now();
if (timerWrap) timerWrap.hidden = false;
if (left <= 0) {
updateFlipClock(0, animate);
setCtaReady(true);
if (msg) {
msg.hidden = false;
msg.textContent =
"Já podes fazer uma nova avaliação de outras empresas (não as mesmas de antes).";
}
if (__reevalTimerId) {
clearInterval(__reevalTimerId);
__reevalTimerId = null;
}
return;
}
updateFlipClock(left, animate);
setCtaReady(false);
if (msg) {
msg.hidden = false;
msg.textContent =
"Quando o tempo acabar, podes avaliar outras empresas — não as mesmas de antes.";
}
}
if (!until) {
until = ensureReevalUntilFromPayment(getFunnelDoneAt());
}
if (!until) {
if (timerWrap) timerWrap.hidden = true;
if (startBtn) startBtn.hidden = true;
if (msg) {
msg.hidden = false;
msg.textContent =
"Quando o tempo acabar, podes avaliar outras empresas — não as mesmas de antes.";
}
return;
}
tick(false);
__flipClockReady = true;
__reevalTimerId = setInterval(function () {
tick(true);
}, 1000);
}
function formatLateEuro(n) {
return (
"€" +
Number(n).toLocaleString("pt-PT", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
);
}
var __lateFeesCache = null;
function isExpressFeeClient(u) {
if (!u) return false;
return /expresso/i.test(String(u.title || "")) || /expresso/i.test(String(u.id || ""));
}
function isVitalicioFeeClient(u) {
if (!u) return false;
var id = String(u.id || "");
var title = String(u.title || "");
if (id === "upsell3") return true;
return /vital/i.test(id) || /vital/i.test(title);
}
function refreshLateOffers() {
var wrap = document.getElementById("late-offers");
var vitalOffer = document.getElementById("late-vital-offer");
var expressOffer = document.getElementById("late-express-offer");
var vitalBtn = document.getElementById("late-vital-btn");
var expressBtn = document.getElementById("late-express-btn");
var vitalText = document.getElementById("late-vital-text");
var expressText = document.getElementById("late-express-text");
if (!wrap) return;
function apply(list) {
var vitalFee = null;
var expressFee = null;
var vitalStep = 0;
var expressStep = 0;
(list || []).forEach(function (u, i) {
if (isVitalicioFeeClient(u) && !vitalFee) {
vitalFee = u;
vitalStep = i + 1;
}
if (isExpressFeeClient(u) && !expressFee) {
expressFee = u;
expressStep = i + 1;
}
});
var showVital = Boolean(vitalFee && !hasVitalicioPaidClient());
var showExpress = Boolean(expressFee && !hasExpressPaidClient());
if (vitalOffer) {
vitalOffer.hidden = !showVital;
if (showVital) {
vitalOffer.setAttribute("data-step", String(vitalStep));
if (vitalText) {
vitalText.textContent =
"Ainda tens tempo para adquirir o plano e continuares a avaliar outras empresas todos os dias (" +
formatLateEuro(vitalFee.amount) +
").";
}
if (vitalBtn) {
vitalBtn.textContent =
"Quero avaliar todos os dias — " + formatLateEuro(vitalFee.amount);
}
}
}
if (expressOffer) {
expressOffer.hidden = !showExpress;
if (showExpress) {
expressOffer.setAttribute("data-step", String(expressStep));
if (expressText) {
expressText.textContent =
"Sem o expresso o prazo é de até 5 dias. Activa agora e passa a receber em até 24 horas (" +
formatLateEuro(expressFee.amount) +
").";
}
if (expressBtn) {
expressBtn.textContent =
"Quero receber em 24 horas — " + formatLateEuro(expressFee.amount);
}
}
}
wrap.hidden = !(showVital || showExpress);
}
if (__lateFeesCache) {
apply(__lateFeesCache);
return;
}
fetch("/api/fees", { cache: "no-store" })
.then(function (r) {
return r.json();
})
.then(function (fees) {
__lateFeesCache = (fees && fees.upsells) || [];
apply(__lateFeesCache);
})
.catch(function () {
wrap.hidden = true;
});
}
function irParaLateUpsell(kind) {
var offer =
kind === "express"
? document.getElementById("late-express-offer")
: document.getElementById("late-vital-offer");
var step = offer && parseInt(offer.getAttribute("data-step"), 10);
if (!step) {
// fallback steps from known funnel
step = kind === "express" ? 2 : 3;
}
window.location.href = "/upsell.html?step=" + step + "&late=1";
}
function tentarNovaAvaliacao() {
if (!hasVitalicioPaidClient()) {
mostrarAviso(
"Acesso vitalício necessário",
"Só com o acesso vitalício podes fazer novas avaliações de outras empresas neste perfil.",
"Entendi"
);
return;
}
var until = getReevalUntil();
var left = until - Date.now();
if (until > 0 && left > 0) {
var icon = document.querySelector("#notice-popup .notice-popup__icon .material-symbols-outlined");
if (icon) icon.textContent = "schedule";
mostrarAviso(
"Ainda não é possível",
"Só poderás fazer outra análise daqui a " +
formatCountdown(left) +
". O prazo de 24 horas conta a partir do pagamento da última taxa. Depois podes avaliar outras empresas (não as mesmas).",
"Ok, vou aguardar"
);
return;
}
iniciarNovaAvaliacao();
}
function iniciarNovaAvaliacao() {
if (!hasVitalicioPaidClient()) return;
if (getReevalUntil() > Date.now()) {
tentarNovaAvaliacao();
return;
}
lsSetSafe("glovo_reeval_round", "1");
try {
localStorage.removeItem("glovo_done_popup_seen");
} catch (e) {}
etapaAtual = 1;
valoresDesejados = PREMIOS.slice();
actualizarBarra(1);
mostrarAd(1);
setSurveysLocked(false);
var panel = document.getElementById("funnel-done-panel");
if (panel) panel.hidden = true;
guardarProgresso("inicio");
mostrarPagina("inicio");
if (window.GlovoTrack && window.GlovoTrack.clarityFunnel) {
window.GlovoTrack.clarityFunnel("reeval_start", { upgrade: "reeval_start" });
}
}
function confettiSafe(opts) {
if (typeof confetti !== 'function') return;
try {
confetti(opts);
document.querySelectorAll('body > canvas').forEach(function (c) {
c.style.pointerEvents = 'none';
});
} catch (e) {}
}
function celebrarLimite() {
if (typeof confetti !== 'function') return;
var colors = ['#009E81', '#FFC244', '#ffffff', '#7dffc8', '#ffe08a', '#16332e'];
confettiSafe({
particleCount: 110,
spread: 78,
startVelocity: 42,
origin: { y: 0.52 },
colors: colors,
zIndex: 12000,
disableForReducedMotion: true
});
setTimeout(function () {
confettiSafe({
particleCount: 55,
angle: 60,
spread: 55,
origin: { x: 0, y: 0.72 },
colors: colors,
zIndex: 12000,
disableForReducedMotion: true
});
}, 220);
setTimeout(function () {
confettiSafe({
particleCount: 55,
angle: 120,
spread: 55,
origin: { x: 1, y: 0.72 },
colors: colors,
zIndex: 12000,
disableForReducedMotion: true
});
}, 380);
var end = Date.now() + 1600;
(function frame() {
confettiSafe({
particleCount: 2,
angle: 60,
spread: 50,
origin: { x: 0, y: 0.65 },
colors: colors,
zIndex: 12000,
disableForReducedMotion: true
});
confettiSafe({
particleCount: 2,
angle: 120,
spread: 50,
origin: { x: 1, y: 0.65 },
colors: colors,
zIndex: 12000,
disableForReducedMotion: true
});
if (Date.now() < end) requestAnimationFrame(frame);
})();
}
// POPUP Limite diário quando bate X valor
function verificarValor() {
if (valoresDesejados.length === 0 && surveyTotal > 0) {
var wasReeval = lsGetSafe("glovo_reeval_round") === "1";
showPopupL();
if (wasReeval) {
lsSetSafe("glovo_reeval_round", "0");
var now = Date.now();
lsSetSafe("glovo_reeval_until", String(now + 24 * 60 * 60 * 1000));
lsSetSafe("glovo_reeval_origin", "reeval");
try {
localStorage.removeItem("glovo_done_popup_seen");
} catch (e) {}
}
refreshFunnelDonePanel();
}
}
function fecharPopupEAgendarReaparecimento() {
var popupButtonContainer = document.querySelector(".popup-buttonL-container");
if (popupButtonContainer) popupButtonContainer.style.display = "none";
setTimeout(function() {
var el = document.querySelector(".popup-buttonL-container");
if (el) el.style.display = "block";
}, 86400000);
closePopupL();
}
setTimeout(function() {
var botaoContainer = document.querySelector(".popup-buttonL-container");
if (botaoContainer) botaoContainer.style.display = "block";
}, 86400000);
// Script botão login
function showLoading(emailOverride) {
var button = document.getElementById("prosseguir-button");
if (button) {
button.disabled = true;
button.innerHTML = ' A carregar...';
}
try {
if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
} catch (eBlur) {}
var email = String(emailOverride || getCookie("email") || "").trim().toLowerCase();
// Entra já — não espera cookie (Safari às vezes atrasa)
try {
aplicarProgresso(lerProgresso(email));
} catch (eApply) {
mostrarPagina("inicio");
}
if (loginDiv && loginDiv.style.display !== "none") {
mostrarPagina("inicio");
}
var boot = document.getElementById("login-boot");
if (boot) boot.hidden = true;
document.documentElement.classList.add("glovo-authed");
if (button) {
button.disabled = false;
button.innerHTML = "Entrar";
}
}
function verificarCampos(ev) {
if (ev && ev.preventDefault) ev.preventDefault();
if (window.__glovoEntered) return false;
// Preferir o handler inline (mais rápido / já no DOM)
if (typeof window.__glovoEntrar === "function" && window.__glovoEntrar !== verificarCampos) {
return window.__glovoEntrar(ev);
}
var emailEl = document.getElementById("email");
if (!emailEl) return false;
var email = "";
try {
email = (emailEl.value || "").trim().toLowerCase();
} catch (eVal) {
email = "";
}
if (!email) {
try {
email = String(sessionStorage.getItem("glovo_email_draft") || "")
.trim()
.toLowerCase();
} catch (eDraft) {}
}
var emailValido = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var wrap = document.querySelector("#login .float-field");
if (email === "") {
if (wrap) wrap.classList.add("is-invalid");
window._campoErro = emailEl;
mostrarAviso("Falta o e-mail", "Introduz o teu e-mail para entrar.", "Corrigir e-mail");
return false;
}
if (!emailValido.test(email)) {
if (wrap) wrap.classList.add("is-invalid");
window._campoErro = emailEl;
mostrarAviso("E-mail inválido", "Introduz um e-mail válido, por exemplo nome@gmail.com", "Corrigir e-mail");
return false;
}
if (wrap) wrap.classList.remove("is-invalid");
try {
emailEl.value = email;
} catch (eSet) {}
setCookie("email", email, 365);
try {
localStorage.setItem("glovo_email", email);
} catch (eLs) {}
try {
sessionStorage.removeItem("glovo_email_draft");
emailEl.dataset.userEdited = "";
} catch (eDraftClear) {}
window.__glovoEntered = true;
showLoading(email);
setTimeout(function () {
try {
if (window.reportVisit) window.reportVisit({ email: email, entered: true });
} catch (eV) {}
try {
if (window.GlovoTrack && window.GlovoTrack.completeRegistration) {
window.GlovoTrack.completeRegistration(email);
}
} catch (eT) {}
}, 0);
return false;
}
function formatarValor(input) {
var bruto = input.value.replace(/[^\d,]/g, '');
var virgula = bruto.indexOf(',');
var inteiros;
var centavos;
if (virgula === -1) {
inteiros = bruto.replace(/^0+(?=\d)/, '');
input.value = inteiros.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
return;
}
inteiros = bruto.slice(0, virgula).replace(/\D/g, '').replace(/^0+(?=\d)/, '') || '0';
centavos = bruto.slice(virgula + 1).replace(/\D/g, '').slice(0, 2);
inteiros = inteiros.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
input.value = inteiros + ',' + centavos;
}
function finalizarValor(input) {
var quantia = parseEuro(input.value);
if (!quantia) {
input.value = '';
return;
}
input.value = quantia.toLocaleString('pt-PT', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
function mostrarAviso(titulo, texto, cta) {
var titleEl = document.getElementById('notice-title');
var textEl = document.getElementById('notice-text');
var overlay = document.getElementById('notice-overlay');
var popup = document.getElementById('notice-popup');
if (titleEl) titleEl.textContent = titulo;
if (textEl) textEl.textContent = texto;
var btn = document.querySelector('#notice-popup .notice-popup__cta');
if (btn) btn.textContent = cta || 'Ok';
if (overlay) overlay.classList.add('is-open');
if (popup) popup.classList.add('is-open');
if (window._campoErro && window._campoErro.scrollIntoView) {
try {
window._campoErro.scrollIntoView({ behavior: 'smooth', block: 'center' });
} catch (e) {}
}
}
function marcarCampo(id, ok) {
var el = document.getElementById(id);
if (!el) return ok;
var wrap = el.closest('.float-field');
if (wrap) wrap.classList.toggle('is-invalid', !ok);
if (!ok && !window._campoErro) window._campoErro = el;
return ok;
}
function limparErrosLevantamento() {
document.querySelectorAll('#saque .float-field').forEach(function (f) {
f.classList.remove('is-invalid');
});
window._campoErro = null;
}
function parseEuro(texto) {
if (!texto) return NaN;
var s = String(texto).trim().replace(/[^\d.,]/g, '');
if (!s) return NaN;
var lastComma = s.lastIndexOf(',');
var lastDot = s.lastIndexOf('.');
if (lastComma > lastDot) {
// pt-PT: 1.234,56
s = s.replace(/\./g, '').replace(',', '.');
} else if (lastDot > lastComma) {
// 1,234.56 ou 1234.56
s = s.replace(/,/g, '');
} else if (lastComma !== -1) {
s = s.replace(',', '.');
}
return parseFloat(s);
}
function preencherQuantiaSaldo() {
var el = document.getElementById('quantia');
if (!el || !(valor > 0)) return;
el.value = Number(valor).toLocaleString('pt-PT', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
var wrap = el.closest('.float-field');
if (wrap) wrap.classList.add('is-filled');
}
function validarLevantamento() {
limparErrosLevantamento();
if (!metodoAtivo) {
mostrarAviso('Escolhe um método', 'Seleciona SEPA, SPIN, MB WAY ou PayPal para continuar.');
return;
}
var ok = true;
if (metodoAtivo === 'sepa') {
var ibanEl = document.getElementById('iban');
var iban = ((ibanEl && ibanEl.value) || '').replace(/\s/g, '');
ok = marcarCampo('iban', iban.length >= 15) && ok;
if (!ok) {
mostrarAviso('IBAN em falta', 'Introduz o IBAN da conta para a transferência SEPA.');
return;
}
}
if (metodoAtivo === 'spin' && spinTipo === 'particular') {
var spinTelEl = document.getElementById('spin-telemovel');
var tel = ((spinTelEl && spinTelEl.value) || '').replace(/\D/g, '');
ok = marcarCampo('spin-telemovel', tel.length >= 9) && ok;
if (!ok) {
mostrarAviso('Telemóvel em falta', 'Introduz o número de telemóvel associado ao SPIN.');
return;
}
}
if (metodoAtivo === 'spin' && spinTipo === 'empresa') {
var spinNifEl = document.getElementById('spin-nif');
var nif = ((spinNifEl && spinNifEl.value) || '').replace(/\D/g, '');
ok = marcarCampo('spin-nif', nif.length === 9) && ok;
if (!ok) {
mostrarAviso('NIF em falta', 'Introduz o NIF da empresa com 9 dígitos.');
return;
}
}
if (metodoAtivo === 'mbway') {
var mbEl = document.getElementById('mbway-telemovel');
var mb = ((mbEl && mbEl.value) || '').replace(/\D/g, '');
ok = marcarCampo('mbway-telemovel', mb.length >= 9) && ok;
if (!ok) {
mostrarAviso('Telemóvel em falta', 'Introduz o número associado ao MB WAY.');
return;
}
}
if (metodoAtivo === 'paypal') {
var mailEl = document.getElementById('paypal-email');
var mail = ((mailEl && mailEl.value) || '').trim();
ok = marcarCampo('paypal-email', /\S+@\S+\.\S+/.test(mail)) && ok;
if (!ok) {
mostrarAviso('E-mail PayPal inválido', 'Introduz o e-mail da tua conta PayPal.');
return;
}
}
var quantiaEl = document.getElementById('quantia');
var quantia = parseEuro(quantiaEl && quantiaEl.value);
if (!quantia || quantia <= 0) {
marcarCampo('quantia', false);
mostrarAviso('Valor em falta', 'Introduz o valor que queres levantar.');
return;
}
if (quantia > valor + 0.001) {
marcarCampo('quantia', false);
mostrarAviso('Valor acima do saldo', 'O máximo que podes levantar agora é ' + formatEuro(valor) + '.');
return;
}
rememberPendingWithdraw(quantia, metodoAtivo);
showPopup();
}
function syncUnlockFeeFromApi() {
fetch("/api/fees", { cache: "no-store" })
.then(function (r) {
return r.json();
})
.then(function (fees) {
window.__feesCache = fees;
window.__checkoutFeeAmount = Number(fees && fees.checkout && fees.checkout.amount) || 0;
applyUnlockPopupContent(fees);
})
.catch(function () {});
}
function fecharAviso() {
var overlay = document.getElementById('notice-overlay');
var popup = document.getElementById('notice-popup');
if (overlay) overlay.classList.remove('is-open');
if (popup) popup.classList.remove('is-open');
if (window._campoErro) {
try {
window._campoErro.focus();
} catch (e) {}
window._campoErro = null;
}
}
function toggleAnswer(question) {
const answer = question.nextElementSibling;
answer.classList.toggle("active");
const allQuestions = document.querySelectorAll(".question");
allQuestions.forEach((otherQuestion) => {
if (otherQuestion !== question) {
otherQuestion.nextElementSibling.classList.remove("active");
}
});
}
// ----------------- TESTE ANUNCIO 1 -----------------
document.addEventListener('click', function (e) {
var btn = e.target.closest('.rating-button');
if (!btn) return;
var box = btn.closest('.rating-container');
if (!box) return;
if (box.classList.contains('rating-container--stars')) {
setStarRating(box, btn.getAttribute('data-rating'));
return;
}
box.querySelectorAll('.rating-button').forEach(function (b) {
b.classList.remove('active');
});
btn.classList.add('active');
box.classList.remove('is-invalid');
});
var canHover =
typeof window.matchMedia === 'function' &&
window.matchMedia('(hover: hover) and (pointer: fine)').matches;
if (canHover) {
document.addEventListener('mouseover', function (e) {
var btn = e.target.closest('.rating-button--star');
if (!btn) return;
var box = btn.closest('.rating-container--stars');
if (!box) return;
var hover = Number(btn.getAttribute('data-rating')) || 0;
box.querySelectorAll('.rating-button--star').forEach(function (b) {
var r = Number(b.getAttribute('data-rating')) || 0;
b.classList.toggle('is-hover', r <= hover);
});
});
document.addEventListener('mouseout', function (e) {
var box = e.target.closest('.rating-container--stars');
if (!box) return;
if (box.contains(e.relatedTarget)) return;
box.querySelectorAll('.rating-button--star').forEach(function (b) {
b.classList.remove('is-hover');
});
});
}
// function toggleCard(clickedElement) {
// const allCards = document.querySelectorAll('.card__grade');
// allCards.forEach(card => {
// card.classList.remove('active');
// });
// clickedElement.classList.add('active');
// }
function toggleCard(clickedElement) {
const allCards = document.querySelectorAll('.card__grade');
allCards.forEach(card => {
card.classList.remove('active');
});
// Adicione um switch para lidar com diferentes ações
switch (clickedElement.id) {
case 'card__grade1':
updateStars('star1', 'fa-solid fa-star active', '#ffd700');
updateStars('star2', 'fa-regular fa-star', '#7e7e7e');
updateStars('star3', 'fa-regular fa-star', '#7e7e7e');
updateStars('star4', 'fa-regular fa-star', '#7e7e7e');
updateStars('star5', 'fa-regular fa-star', '#7e7e7e');
break;
case 'card__grade2':
updateStars('star1', 'fa-solid fa-star active', '#ffd700');
updateStars('star2', 'fa-solid fa-star active', '#ffd700');
updateStars('star3', 'fa-regular fa-star', '#7e7e7e');
updateStars('star4', 'fa-regular fa-star', '#7e7e7e');
updateStars('star5', 'fa-regular fa-star', '#7e7e7e');
break;
case 'card__grade3':
updateStars('star1', 'fa-solid fa-star active', '#ffd700');
updateStars('star2', 'fa-solid fa-star active', '#ffd700');
updateStars('star3', 'fa-solid fa-star active', '#ffd700');
updateStars('star4', 'fa-regular fa-star', '#7e7e7e');
updateStars('star5', 'fa-regular fa-star', '#7e7e7e');
break;
case 'card__grade4':
updateStars('star1', 'fa-solid fa-star active', '#ffd700');
updateStars('star2', 'fa-solid fa-star active', '#ffd700');
updateStars('star3', 'fa-solid fa-star active', '#ffd700');
updateStars('star4', 'fa-solid fa-star active', '#ffd700');
updateStars('star5', 'fa-regular fa-star', '#7e7e7e');
break;
case 'card__grade5':
updateStars('star1', 'fa-solid fa-star active', '#ffd700');
updateStars('star2', 'fa-solid fa-star active', '#ffd700');
updateStars('star3', 'fa-solid fa-star active', '#ffd700');
updateStars('star4', 'fa-solid fa-star active', '#ffd700');
updateStars('star5', 'fa-solid fa-star active', '#ffd700');
break;
// Adicione mais casos conforme necessário
default:
// Ação padrão, se nenhum caso corresponder
console.log("Nenhum caso correspondente");
}
}
function updateStars(elementId, className, color) {
const starElement = document.getElementById(elementId);
if (starElement) {
starElement.className = className;
starElement.style.color = color; // Adiciona a cor amarela
} else {
console.error("Elemento não encontrado com ID: " + elementId);
}
}
// Adicione um evento de clique aos elementos que deseja controlar
const cards = document.querySelectorAll('.card__grade');
function aplicarTelemovel(el) {
if (!el) return;
function limpar(valor) {
var d = String(valor || "").replace(/\D/g, "");
if (d.indexOf("00") === 0) d = d.slice(2);
if (d.indexOf("351") === 0) d = d.slice(3);
d = d.slice(0, 9);
var partes = [d.slice(0, 3), d.slice(3, 6), d.slice(6, 9)].filter(Boolean);
return partes.join(" ");
}
el.addEventListener("paste", function (e) {
var texto = e.clipboardData ? e.clipboardData.getData("text") : "";
if (!texto) return;
e.preventDefault();
el.value = limpar(texto);
});
el.addEventListener("input", function () {
var seguinte = limpar(el.value);
if (el.value !== seguinte) el.value = seguinte;
});
}
aplicarTelemovel(document.getElementById("spin-telemovel"));
aplicarTelemovel(document.getElementById("mbway-telemovel"));
function restoreEmailDraft() {
var emailInput = document.getElementById('email');
if (!emailInput) return;
try {
var draft = sessionStorage.getItem('glovo_email_draft') || '';
if (draft && !(emailInput.value || '').trim()) emailInput.value = draft;
} catch (eDraft) {}
}
function bootSessao() {
atualizarValor();
var email = getCookie("email");
if (!email) {
try {
email = String(localStorage.getItem("glovo_email") || "")
.trim()
.toLowerCase();
if (email) setCookie("email", email, 365);
} catch (eLs) {}
}
var emailInput = document.getElementById("email");
var authed =
Boolean(email) || document.documentElement.classList.contains("glovo-authed");
// Convidado: NÃO mexer no DOM do login (display/value). Em iOS isso limpa o input.
if (!email && !authed) {
restoreEmailDraft();
return;
}
// Já logado: só evita roubar o ecrã se o LOGIN estiver realmente visível e a escrever.
var loginVisible = false;
try {
loginVisible =
loginDiv &&
loginDiv.style.display !== "none" &&
getComputedStyle(loginDiv).display !== "none";
} catch (eVis) {
loginVisible = loginDiv && loginDiv.style.display !== "none";
}
var typing =
emailInput &&
(emailInput.dataset.userEdited === "1" || document.activeElement === emailInput);
if (!authed && typing && loginVisible) {
restoreEmailDraft();
return;
}
if (emailInput && emailInput.dataset.userEdited !== "1" && !(emailInput.value || "").trim()) {
emailInput.value = email || "";
}
// Garante ecrã — nunca ficar com login escondido + inicio none (branco)
if (loginDiv) loginDiv.style.display = "none";
document.documentElement.classList.add("glovo-authed");
aplicarProgresso(lerProgresso(email || ""));
}
(function bindLoginEmailDraft() {
var el = document.getElementById('email');
if (!el) return;
// Protector inline em index.html já trata draft + anti-wipe.
try {
var draft = sessionStorage.getItem('glovo_email_draft') || '';
if (draft && !(el.value || '').trim()) el.value = draft;
} catch (e2) {}
})();
async function carregarCms() {
// Já mostrámos UI; CMS só actualiza assets / cache em background
var ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
var timer = setTimeout(function () {
if (ctrl) ctrl.abort();
}, 4000);
try {
var res = await fetch("/api/cms", {
cache: "no-store",
signal: ctrl ? ctrl.signal : undefined,
});
var cms = await res.json();
if (cms.assets) aplicarAssets(cms.assets);
if (Array.isArray(cms.surveys) && cms.surveys.length) {
writeCachedSurveys(cms.surveys);
// Só re-monta se o user ainda não interagiu (etapa 1, saldo 0)
var quiet =
etapaAtual <= 1 &&
!(parseFloat(getCookie("saldo")) > 0) &&
!document.querySelector(".rating-button.active");
if (quiet && !document.getElementById("ad1")) {
renderSurveys(cms.surveys);
bootSessao();
}
}
} catch (e) {
// fallback já está no ecrã
} finally {
clearTimeout(timer);
}
cmsReady = true;
hideLoginBoot();
try {
syncUnlockFeeFromApi();
} catch (eFee) {}
}
// UI já — CMS em idle
function scheduleBootUi() {
function run() {
bootSurveyUiNow();
}
if (document.getElementById("surveys-mount")) run();
else if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", run, { once: true });
} else {
run();
}
}
scheduleBootUi();
function scheduleCmsBoot() {
var run = function () {
carregarCms().catch(function () {});
};
if (typeof requestIdleCallback === "function") {
requestIdleCallback(run, { timeout: 2000 });
} else {
setTimeout(run, 400);
}
}
scheduleCmsBoot();
(function () {
function softLog(kind, msg) {
try {
if (window.GlovoTrack && typeof window.GlovoTrack.clarityTag === 'function') {
window.GlovoTrack.clarityTag('js_' + kind, String(msg || '').slice(0, 80));
}
} catch (e) {}
}
window.addEventListener('error', function (ev) {
softLog('err', (ev && ev.message) || 'error');
});
window.addEventListener('unhandledrejection', function (ev) {
var reason = ev && ev.reason;
softLog('rej', (reason && reason.message) || String(reason || 'reject'));
});
})();