// ---
// Simple Adblock Detector - Optimized Version
// Telegram: @nulled_g
// Created by: NulledNyc
// ---

/**
 * Realiza una comprobación de recurso para detectar AdBlock
 * @param {string} url URL a comprobar
 * @param {object} options Opciones para fetch
 * @returns {Promise<boolean>} true si se detecta AdBlock
 */
const resourceCheck = async (url, options = {}) => {
    try {
        const resp = await fetch(url, options);
        await resp.text();
        return false;
    } catch (e) {
        return true;
    }
}

// Lista de recursos comunes bloqueados por AdBlockers
const adResources = [
    { url: "https://widgets.outbrain.com/outbrain.js" },
    { url: "https://adligature.com/", options: { mode: "no-cors" } },
    { url: "https://secure.quantserve.com/quant.js", options: { mode: "no-cors" } },
    { url: "https://cdn.adligature.com/work.ink/prod/rules.css", options: { mode: "no-cors" } },
    { url: "https://srvtrck.com/assets/css/LineIcons.css", options: { mode: "no-cors" } }
];

/**
 * Comprueba elementos DOM que suelen ser bloqueados
 * @returns {boolean} true si se detecta AdBlock
 */
const domElementCheck = () => {
    const bannerIds = ['AdHeader', 'AdContainer', 'AD_Top', 'homead', 'ad-lead'];
    const fragment = document.createDocumentFragment();
    const container = document.createElement("div");
    
    // Crear elementos de prueba
    bannerIds.forEach(id => {
        const div = document.createElement("div");
        div.id = id;
        div.innerHTML = "&nbsp;";
        div.style.height = "1px"; // Asegurar que tiene altura
        container.appendChild(div);
    });
    
    fragment.appendChild(container);
    document.body.appendChild(fragment);
    
    // Comprobar elementos
    const adblockDetected = bannerIds.some(id => {
        const elem = document.getElementById(id);
        const isHidden = !elem || elem.offsetHeight === 0;
        elem?.remove();
        return isHidden;
    });
    
    return adblockDetected;
}

/**
 * Comprueba si setInterval es modificado (algunos AdBlockers lo hacen)
 * @returns {Promise<boolean>} true si se detecta AdBlock
 */
const intervalCheck = () => {
    return new Promise((resolve) => {
        const timeout = setTimeout(() => resolve(true), 2000);
        const interval = setInterval(() => {
            clearInterval(interval);
            clearTimeout(timeout);
            resolve(false);
        }, 100);
    });
}

/**
 * Detecta si hay un AdBlock activo
 * @returns {Promise<boolean>} true si se detecta AdBlock
 */
const detectAdBlock = async () => {
    try {
        // Comprobar recursos en paralelo
        const resourceChecks = await Promise.all(
            adResources.map(r => resourceCheck(r.url, r.options || {}))
        );
        
        // Otras comprobaciones
        const [domCheck, intervalCheckResult] = await Promise.all([
            domElementCheck(),
            intervalCheck()
        ]);
        
        // Si alguna comprobación es positiva
        return resourceChecks.some(r => r) || domCheck || intervalCheckResult;
    } catch (error) {
        console.error("Error detecting adblock:", error);
        return false; // En caso de error, asumir que no hay AdBlock
    }
};

/**
 * Función para desactivar el click derecho
 */
const disableRightClick = () => {
    document.addEventListener('contextmenu', (e) => {
        e.preventDefault();
    });
};

/**
 * Muestra el SweetAlert de AdBlock detectado
 */
const showAdBlockAlert = () => {
    // Desactivar click derecho
    disableRightClick();
    
    // Cargar SweetAlert si no está cargado
    if (typeof Swal === 'undefined') {
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/sweetalert2@11';
        script.onload = () => showAdBlockAlert();
        document.head.appendChild(script);
        
        const style = document.createElement('link');
        style.rel = 'stylesheet';
        style.href = 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css';
        document.head.appendChild(style);
        return;
    }
    
    // Mostrar el SweetAlert
    Swal.fire({
        title: '<strong><i class="bi bi-emoji-frown"></i> AdBlock Detected <i class="bi bi-emoji-frown"></i></strong>',
        html: '<i class="bi bi-info-circle"></i> Hemos detectado que está utilizando extensiones para bloquear anuncios. <br><br>Por favor, ayúdenos deshabilitando este bloqueador de anuncios.',
        icon: "info",
        showCloseButton: false,
        showCancelButton: false,
        showConfirmButton: true,
        confirmButtonText: 'Close and Reload <i class="bi bi-arrow-clockwise"></i>',
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        backdrop: 'rgba(0,0,0,0.5)',
        customClass: {
            popup: 'adblock-swal',
            title: 'adblock-swal-title',
            confirmButton: 'adblock-swal-confirm-btn'
        },
        didOpen: () => {
            // Añadir estilos adicionales
            const style = document.createElement('style');
            style.textContent = `
                .adblock-swal {
                    border-radius: 10px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                    max-width: 600px;
                    width: 80%;
                }
                
                .adblock-swal-title {
                    color: #1393c3;
                    background: linear-gradient(0deg, #1393c3 0%, #57b58c 100%);
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                    margin-bottom: 15px;
                }
                
                .adblock-swal-confirm-btn {
                    background-color: #3498db !important;
                    font-size: 16px;
                    transition: background-color 0.3s;
                    padding: 10px 20px;
                    border-radius: 5px;
                }
                
                .adblock-swal-confirm-btn:hover {
                    background-color: #2980b9 !important;
                }
                
                .swal2-image {
                    margin-bottom: 15px;
                }
            `;
            document.head.appendChild(style);
            
            // Añadir fuentes de Bootstrap Icons si no están presentes
            if (!document.querySelector('link[href*="bootstrap-icons"]')) {
                const iconFont = document.createElement('link');
                iconFont.rel = 'stylesheet';
                iconFont.href = 'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css';
                document.head.appendChild(iconFont);
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            location.reload();
        }
    });
};

// Inicialización
(async () => {
    const adBlockDetected = await detectAdBlock();
    if (adBlockDetected) {
        showAdBlockAlert();
    }
})();
