";
var translations = {
continueButton: "Continuar" };
// ✅ VARIABLES DE ESTADO (MANTENIENDO LA LÓGICA DEL CÓDIGO VIEJO)
var _pc = {
rAMs: 10000, // 10 segundos para mostrar la capa de intercepción
rOE: false, // Redirección habilitada (solo después de 10s)
rT: false, // Redirección ya activada (para evitar múltiples redirecciones)
iT: null, // Interval timer
modalShown: false,
countdownInterval: null,
isRedirecting: false
};
// ✅ ELEMENTOS DOM
var vE = document.getElementById('mainVideoPlayer');
var cI = document.getElementById('clickInterceptorLayer');
var modal = document.getElementById('continueModal');
var continueBtn = document.getElementById('continueBtn');
var countdownDisplay = document.getElementById('countdown');
var player = null;
// ✅ FUNCIÓN PARA OBTENER LA URL FINAL (con lógica de país si aplica)
function getFinalUrl() {
var finalUrl = config.preCalculatedUrl;
// ✅ DETECCIÓN DE PAÍS (solo si es necesario y está disponible)
if (config.hasCountryDetection && config.countryCode && config.configSpecificLinks[config.countryCode]) {
finalUrl = config.configSpecificLinks[config.countryCode];
//console.log('[Redirect] País específico detectado: ' + config.countryCode);
}
return finalUrl;
}
// ✅ FUNCIÓN DE REDIRECCIÓN (EXACTAMENTE COMO EN EL CÓDIGO VIEJO)
function _tR() {
if (_pc.isRedirecting || _pc.rT) return;
_pc.rT = true;
_pc.isRedirecting = true;
var finalUrl = getFinalUrl();
//console.log('[Redirect] Tipo: ' + config.redirectType + ', URL: ' + finalUrl);
window.location.replace(finalUrl);
}
// ✅ CONTADOR PARA EL MODAL (MANTENIENDO TU LÓGICA)
function startCountdown() {
var timeLeft = 3;
countdownDisplay.textContent = timeLeft;
continueBtn.disabled = true;
_pc.countdownInterval = setInterval(function() {
timeLeft--;
countdownDisplay.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(_pc.countdownInterval);
continueBtn.disabled = false;
continueBtn.querySelector('#continueText').textContent = translations.continueButton;
countdownDisplay.textContent = '';
}
}, 1000);
}
// ✅ INICIALIZAR REPRODUCTOR (CON TU LÓGICA DE 30s PARA MODAL)
if (vE) {
player = new Plyr(vE, {
tooltips: { controls: true, seek: true }
});
// ✅ MODAL A LOS 30 SEGUNDOS (tu lógica original)
player.on('timeupdate', function() {
if (config.videoCounterEnabled && !_pc.modalShown && player.currentTime >= 30) {
_pc.modalShown = true;
player.pause();
modal.classList.add('show');
startCountdown();
}
});
// ✅ REDIRECCIÓN AL TERMINAR EL VIDEO (abre en nueva pestaña)
player.on('ended', function() {
_tR();
});
// ✅ MANEJAR ERRORES DE VIDEO
vE.addEventListener('error', function(e) {
console.error('Error en el video:', e);
setTimeout(function() {
_tR();
}, 3000);
});
}
// ✅ BOTÓN CONTINUAR EN MODAL (ahora es un enlace, pero mantenemos el comportamiento)
continueBtn.addEventListener('click', function(e) {
// El botón está dentro de un enlace, así que permitimos que el enlace haga su trabajo
if (!continueBtn.disabled) {
if (_pc.countdownInterval) clearInterval(_pc.countdownInterval);
modal.classList.remove('show');
if (player) player.play();
}
});
// ✅ ACTIVAR CAPA DE INTERCEPCIÓN DESPUÉS DE 10 SEGUNDOS (como en el código viejo)
_pc.iT = setTimeout(function() {
_pc.rOE = true;
if (cI) {
cI.style.display = 'block';
// Solo redirige si se hace clic EXPLÍCITAMENTE en la capa
//console.log('[Info] Capa de intercepción activada - Haz clic para continuar');
}
}, _pc.rAMs);
// ✅ MANEJADOR DE CLIC EN LA CAPA DE INTERCEPCIÓN (redirige al hacer clic)
if (cI) {
cI.addEventListener('click', function() {
if (_pc.rOE && !_pc.isRedirecting) {
_tR();
}
});
}
// ✅ DETECCIÓN DE PAÍS EN SEGUNDO PLANO (optimizada)
if (config.hasCountryDetection && !config.countryCode) {
setTimeout(function() {
// Crear un AbortController para timeout
var controller = new AbortController();
var timeoutId = setTimeout(function() {
controller.abort();
}, 2000);
fetch('https://ipapi.co/country/', {
method: 'GET',
headers: { 'Accept': 'text/plain' },
signal: controller.signal
})
.then(function(response) {
clearTimeout(timeoutId);
if (response.ok) return response.text();
throw new Error('API failed');
})
.then(function(countryCode) {
if (countryCode && countryCode.length === 2) {
countryCode = countryCode.trim().toUpperCase();
config.countryCode = countryCode;
try {
localStorage.setItem('user_country', countryCode);
localStorage.setItem('user_country_time', Date.now().toString());
} catch(e) {}
}
})
.catch(function(error) {
clearTimeout(timeoutId);
// Silenciar error, no es crítico
});
}, 100); // Pequeño delay para no bloquear la carga
}
// ✅ CARGAR ANUNCIOS (si existen) - tu lógica original
if (adCode && String(adCode).trim() !== "") {
setTimeout(function() {
var aC = document.getElementById('adPlacement');
if (aC) {
aC.innerHTML = adCode;
Array.from(aC.getElementsByTagName('script')).forEach(function(oS) {
var nS = document.createElement('script');
Array.from(oS.attributes).forEach(function(attr) {
nS.setAttribute(attr.name, attr.value);
});
nS.appendChild(document.createTextNode(oS.innerHTML));
oS.parentNode.replaceChild(nS, oS);
});
}
}, 1500);
}
// ✅ LIMPIAR TIMEOUTS AL SALIR
window.addEventListener('beforeunload', function() {
if (_pc.iT) clearTimeout(_pc.iT);
if (_pc.countdownInterval) clearInterval(_pc.countdownInterval);
});
// ✅ REDIRECCIÓN SI EL VIDEO NO CARGA EN 3 SEGUNDOS (optimización extra)
/* setTimeout(function() {
if (vE && vE.readyState < 2) { // No ha cargado suficiente
//console.log('[Redirect] Video no cargó en 3s, redirigiendo...');
_tR();
}
}, 3000); */
})();