// Anti-Block Script v2.0 - ISP Bypass Helper
(function() {
    'use strict';
    
    // Register Service Worker
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            navigator.serviceWorker.register('/sw.js')
                .then(function(registration) {
                    console.log('[PWA] Service Worker registered:', registration.scope);
                })
                .catch(function(error) {
                    console.log('[PWA] Service Worker registration failed:', error);
                });
        });
    }
    
    // DNS Prefetch - Faster loading
    const dnsPrefetchDomains = [
        'cloudflare-dns.com',
        'dns.google',
        'cdn.jsdelivr.net',
        'cdnjs.cloudflare.com',
        'fonts.googleapis.com',
        'fonts.gstatic.com',
        'dc.crsorgi.gov.in'
    ];
    
    dnsPrefetchDomains.forEach(function(domain) {
        var link = document.createElement('link');
        link.rel = 'dns-prefetch';
        link.href = '//' + domain;
        document.head.appendChild(link);
        
        var preconnect = document.createElement('link');
        preconnect.rel = 'preconnect';
        preconnect.href = 'https://' + domain;
        preconnect.crossOrigin = 'anonymous';
        document.head.appendChild(preconnect);
    });
    
    // Network Monitoring
    var isOnline = navigator.onLine;
    var connectionChecks = 0;
    var maxChecks = 3;
    
    function checkNetwork() {
        return new Promise(function(resolve) {
            var img = new Image();
            var timeout = setTimeout(function() {
                resolve(false);
            }, 5000);
            
            img.onload = function() {
                clearTimeout(timeout);
                resolve(true);
            };
            
            img.onerror = function() {
                clearTimeout(timeout);
                resolve(false);
            };
            
            img.src = 'https://www.google.com/favicon.ico?t=' + Date.now();
        });
    }
    
    // Check if site is blocked
    async function checkSiteAccess() {
        try {
            var response = await fetch(window.location.origin + '/manifest.json', {
                method: 'HEAD',
                cache: 'no-store'
            });
            return response.ok;
        } catch (e) {
            return false;
        }
    }
    
    // Show help modal if blocked
    function showBlockedHelp() {
        if (document.getElementById('blocked-help-modal')) return;
        
        var modal = document.createElement('div');
        modal.id = 'blocked-help-modal';
        modal.innerHTML = `
            <div style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.8);z-index:99999;display:flex;align-items:center;justify-content:center;">
                <div style="background:white;padding:30px;border-radius:15px;max-width:500px;margin:20px;text-align:center;">
                    <h2 style="color:#d32f2f;margin-bottom:20px;">⚠️ Site Access Issue</h2>
                    <p style="margin-bottom:20px;color:#333;">आपका ISP (Airtel/Jio) इस साइट को block कर रहा है।</p>
                    <div style="margin-bottom:20px;">
                        <a href="/access-help.php" style="display:inline-block;background:#1e3c72;color:white;padding:12px 25px;border-radius:25px;text-decoration:none;margin:5px;">
                            📖 Help देखें
                        </a>
                        <button onclick="this.parentElement.parentElement.parentElement.parentElement.remove()" style="display:inline-block;background:#666;color:white;padding:12px 25px;border-radius:25px;border:none;cursor:pointer;margin:5px;">
                            ✕ बंद करें
                        </button>
                    </div>
                    <p style="font-size:12px;color:#666;">DNS बदलें: 8.8.8.8 या 1.1.1.1</p>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }
    
    // PWA Install Prompt
    var deferredPrompt = null;
    
    window.addEventListener('beforeinstallprompt', function(e) {
        e.preventDefault();
        deferredPrompt = e;
        showInstallButton();
    });
    
    function showInstallButton() {
        if (document.getElementById('pwa-install-btn')) return;
        
        var btn = document.createElement('button');
        btn.id = 'pwa-install-btn';
        btn.innerHTML = '📱 App Install करें';
        btn.style.cssText = 'position:fixed;bottom:80px;right:20px;background:linear-gradient(135deg,#667eea,#764ba2);color:white;border:none;padding:12px 20px;border-radius:25px;cursor:pointer;z-index:9998;font-size:14px;box-shadow:0 4px 15px rgba(102,126,234,0.4);';
        
        btn.onclick = async function() {
            if (deferredPrompt) {
                deferredPrompt.prompt();
                var result = await deferredPrompt.userChoice;
                if (result.outcome === 'accepted') {
                    console.log('[PWA] App installed');
                }
                deferredPrompt = null;
                btn.remove();
            }
        };
        
        document.body.appendChild(btn);
    }
    
    // Floating Help Button
    function createHelpButton() {
        if (document.getElementById('floating-help-btn')) return;
        
        var btn = document.createElement('a');
        btn.id = 'floating-help-btn';
        btn.href = '/access-help.php';
        btn.innerHTML = '❓';
        btn.title = 'Site Access Help';
        btn.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#d32f2f;color:white;width:50px;height:50px;border-radius:50%;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:24px;z-index:9997;box-shadow:0 4px 15px rgba(211,47,47,0.4);transition:transform 0.3s;';
        
        btn.onmouseover = function() {
            this.style.transform = 'scale(1.1)';
        };
        btn.onmouseout = function() {
            this.style.transform = 'scale(1)';
        };
        
        document.body.appendChild(btn);
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        createHelpButton();
        
        // Check network after 3 seconds
        setTimeout(async function() {
            var hasInternet = await checkNetwork();
            var siteAccessible = await checkSiteAccess();
            
            if (hasInternet && !siteAccessible) {
                showBlockedHelp();
            }
        }, 3000);
    });
    
    // Online/Offline events
    window.addEventListener('online', function() {
        console.log('[Network] Online');
        isOnline = true;
    });
    
    window.addEventListener('offline', function() {
        console.log('[Network] Offline');
        isOnline = false;
    });
    
    console.log('[Anti-Block] Script loaded');
})();
