/**
 * Safari Reload Loop Prevention System
 * Prevents infinite reload loops that can occur in Safari when page crashes
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

(function() {
    'use strict';
    
    class SafariReloadPrevention {
        constructor() {
            this.threshold = 3;
            this.timeWindow = 10000; // 10 seconds
            this.storageKey = 'hvac_safari_reloads';
            this.checkReloadLoop();
        }
        
        checkReloadLoop() {
            try {
                const data = JSON.parse(sessionStorage.getItem(this.storageKey) || '{"reloads":[]}');
                const now = Date.now();
                
                // Clean old entries outside time window
                data.reloads = data.reloads.filter(time => now - time < this.timeWindow);
                
                // Add current reload timestamp
                data.reloads.push(now);
                
                // Check if we've exceeded reload threshold
                if (data.reloads.length >= this.threshold) {
                    this.handleLoop();
                    return;
                }
                
                // Save updated reload data
                sessionStorage.setItem(this.storageKey, JSON.stringify(data));
                
                console.log('[Safari Reload Prevention] Reload tracked:', data.reloads.length, 'of', this.threshold);
                
            } catch (error) {
                console.error('[Safari Reload Prevention] Error checking reload loop:', error);
            }
        }
        
        handleLoop() {
            console.error('[Safari Reload Prevention] Reload loop detected! Stopping page execution.');
            
            // Clear the reload tracking
            try {
                sessionStorage.removeItem(this.storageKey);
            } catch (e) {
                // Silent fail if storage not available
            }
            
            // Stop any further page loading
            if (window.stop) {
                window.stop();
            }
            
            // Replace page content with user-friendly error message
            document.documentElement.innerHTML = `
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Page Loading Issue</title>
                    <style>
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
                            background: #f5f5f5;
                            color: #333;
                            margin: 0;
                            padding: 0;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            min-height: 100vh;
                        }
                        .error-container {
                            background: white;
                            border-radius: 8px;
                            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                            padding: 40px;
                            max-width: 500px;
                            margin: 20px;
                            text-align: center;
                        }
                        h1 {
                            color: #d9534f;
                            font-size: 24px;
                            margin-bottom: 20px;
                        }
                        p {
                            color: #666;
                            line-height: 1.6;
                            margin-bottom: 20px;
                        }
                        ul {
                            text-align: left;
                            display: inline-block;
                            margin: 20px 0;
                        }
                        li {
                            margin: 10px 0;
                        }
                        .btn {
                            display: inline-block;
                            padding: 12px 30px;
                            background: #007cba;
                            color: white;
                            text-decoration: none;
                            border-radius: 5px;
                            font-weight: 500;
                            margin-top: 20px;
                            transition: background 0.3s;
                        }
                        .btn:hover {
                            background: #005a87;
                        }
                        .icon {
                            font-size: 48px;
                            margin-bottom: 20px;
                        }
                    </style>
                </head>
                <body>
                    <div class="error-container">
                        <div class="icon">⚠️</div>
                        <h1>Page Loading Issue Detected</h1>
                        <p>We've detected an issue loading this page in Safari. This can happen due to browser compatibility issues.</p>
                        <p><strong>Please try one of the following:</strong></p>
                        <ul>
                            <li>Clear your browser cache and cookies</li>
                            <li>Disable browser extensions temporarily</li>
                            <li>Try using Chrome, Firefox, or Edge browsers</li>
                            <li>Update Safari to the latest version</li>
                        </ul>
                        <a href="${window.location.origin}" class="btn">Return to Homepage</a>
                    </div>
                </body>
                </html>
            `;
        }
        
        // Public method to manually reset reload tracking
        reset() {
            try {
                sessionStorage.removeItem(this.storageKey);
                console.log('[Safari Reload Prevention] Reload tracking reset');
            } catch (error) {
                console.error('[Safari Reload Prevention] Error resetting:', error);
            }
        }
    }
    
    // Initialize only on Safari browsers
    if (navigator.userAgent.indexOf('Safari') !== -1 && 
        navigator.userAgent.indexOf('Chrome') === -1 &&
        navigator.userAgent.indexOf('Chromium') === -1) {
        
        // Run immediately to catch reload loops early
        window.hvacSafariReloadPrevention = new SafariReloadPrevention();
        
        console.log('[Safari Reload Prevention] System activated');
    }
})();