(function() {
'use strict';

// Configurações Globais
const CONFIG = {
// Desktop
mouseThreshold: 5, // Pixels mínimos de movimento
minMouseTime: 800, // Tempo mínimo antes do clique

// Mobile
minTouchDuration: 600, // Tempo mínimo pressionando
minScrollDistance: 30, // Scroll mínimo para validar
gyroSensitivity: 2.0, // Sensibilidade do giroscópio

// Geral
unlockDelay: 500, // Delay artístico após validação
timeoutFallback: 6000 // Libera automaticamente se nada acontecer (UX)
};

let state = {
verified: false,
platform: null, // 'desktop' ou 'mobile'
startTime: 0,
movements: 0,
lastX: 0,
lastY: 0,
touchData: null,
scrollAcc: 0,
gyroChanged: false,
lastGyro: { alpha: 0, beta: 0, gamma: 0 }
};

const sensitiveSelectors = ['form', '.secure-content', '#login-panel', 'iframe', '.input-field'];

function initHybridProtection() {
detectPlatform();
obscureElements();
setupListeners();

// Fallback de UX: Se o usuário for muito parado ou o sensor falhar, libera após X segundos
setTimeout(() => {
if (!state.verified) {
console.warn(' Timeout de inatividade. Liberando acesso.');
verifyHuman();
}
}, CONFIG.timeoutFallback);
}

function detectPlatform() {
const isTouchDevice = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
// Prioriza mobile se tiver touch, mesmo que tenha mouse (ex: tablets híbridos)
state.platform = isTouchDevice? 'mobile': 'desktop';
console.log(` Plataforma detectada: ${state.platform.toUpperCase()}`);
}

function obscureElements() {
sensitiveSelectors.forEach(sel => {
document.querySelectorAll(sel).forEach(el => {
el.style.opacity = '0';
el.style.pointerEvents = 'none';
el.setAttribute('data-locked', 'true');
el.style.transition = 'opacity 0.4s ease';
});
});

const overlay = document.createElement('div');
overlay.id = 'hybrid-antibot-overlay';
Object.assign(overlay.style, {
position: 'fixed', top: '0', left: '0', width: '100%', height: '100%',
zIndex: '99999', background: 'transparent', touchAction: 'none'
});
document.body.appendChild(overlay);
}

function setupListeners() {
if (state.platform === 'desktop') {
document.addEventListener('mousemove', onMouseMove, { passive: true });
document.addEventListener('click', onClickDesktop, { once: true });
document.addEventListener('keydown', () => { if(!state.startTime) state.startTime = Date.now(); }, { once: true });
} else {
document.addEventListener('touchstart', onTouchStart, { passive: true });
document.addEventListener('touchmove', onTouchMove, { passive: true });
document.addEventListener('touchend', onTouchEnd, { passive: true });
window.addEventListener('scroll', onScroll, { passive: true });

// Tenta ativar giroscópio se disponível
if (typeof DeviceOrientationEvent!== 'undefined') {
window.addEventListener('deviceorientation', onOrientation, { passive: true });
}
}
}

// --- LÓGICA DESKTOP ---
function onMouseMove(e) {
if (state.verified) return;
if (!state.startTime) state.startTime = Date.now();

const dx = Math.abs(e.clientX - state.lastX);
const dy = Math.abs(e.clientY - state.lastY);

if (dx > CONFIG.mouseThreshold || dy > CONFIG.mouseThreshold) {
state.movements++;
state.lastX = e.clientX;
state.lastY = e.clientY;
}
}

function onClickDesktop(e) {
if (state.verified) return;

const now = Date.now();
const duration = state.startTime? (now - state.startTime): 0;
const hasMovement = state.movements > 3;
const isNaturalTime = duration > CONFIG.minMouseTime;

// Validação: Teve movimento suficiente E demorou um tempo humano?
if (hasMovement && isNaturalTime) {
verifyHuman();
} else {
resetState(); // Bot detectado (clique instantâneo ou sem movimento)
}
}

// --- LÓGICA MOBILE ---
function onTouchStart(e) {
if (state.verified) return;
if (!state.startTime) state.startTime = Date.now();

const t = e.touches;
state.touchData = {
x: t.clientX, y: t.clientY,
force: t.force || 0,
radiusX: t.radiusX || 10,
radiusY: t.radiusY || 10,
startTime: Date.now()
};
}

function onTouchMove(e) {
if (state.verified ||!state.touchData) return;
const t = e.touches;
const dx = Math.abs(t.clientX - state.touchData.x);
const dy = Math.abs(t.clientY - state.touchData.y);

if (dx > 2 || dy > 2) state.touchData.moved = true;
}

function onScroll() {
if (state.verified) return;
state.scrollAcc += 10;
}

function onOrientation(e) {
if (state.verified) return;
const { alpha, beta, gamma } = e;
if (alpha === null) return; // Sensor não disponível

const dA = Math.abs(alpha - state.lastGyro.alpha);
const dB = Math.abs(beta - state.lastGyro.beta);
const dG = Math.abs(gamma - state.lastGyro.gamma);

if (dA > CONFIG.gyroSensitivity || dB > CONFIG.gyroSensitivity || dG > CONFIG.gyroSensitivity) {
state.gyroChanged = true;
}
state.lastGyro = { alpha, beta, gamma };
}

function onTouchEnd(e) {
if (state.verified ||!state.touchData) return;

const duration = Date.now() - state.touchData.startTime;
const isHumanArea = (state.touchData.radiusX > 4 && state.touchData.radiusY > 4);
const isHumanTime = duration > CONFIG.minTouchDuration;
const hasInteraction = state.touchData.moved || state.scrollAcc > CONFIG.minScrollDistance || state.gyroChanged;

// Validação Mobile: Área de dedo real + Tempo humano + Algum movimento físico
if (isHumanArea && isHumanTime && hasInteraction) {
verifyHuman();
} else {
resetState();
}
}

// --- COMUM ---
function resetState() {
console.warn(' Comportamento robótico detectado. Resetando validação.');
state.movements = 0;
state.startTime = 0;
state.touchData = null;
state.gyroChanged = false;
state.scrollAcc = 0;
// Opcional: Adicionar penalidade de tempo aqui
}

function verifyHuman() {
if (state.verified) return;
state.verified = true;

setTimeout(() => {
revealContent();
document.getElementById('hybrid-antibot-overlay')?.remove();
console.log(' Usuário verificado com sucesso.');
}, CONFIG.unlockDelay);
}

function revealContent() {
document.querySelectorAll('[data-locked="true"]').forEach(el => {
el.style.opacity = '1';
el.style.pointerEvents = 'auto';
el.removeAttribute('data-locked');
});
}

// Inicialização
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initHybridProtection);
} else {
initHybridProtection();
}
})();
