/**
 * HVAC Safari Debug System
 * Comprehensive debugging for Safari compatibility issues
 */

(function() {
    'use strict';
    
    // Debug logger that works in all browsers
    var SafariDebug = {
        logs: [],
        
        log: function(message, data) {
            var timestamp = new Date().toISOString();
            var logEntry = {
                time: timestamp,
                message: message,
                data: data || null,
                userAgent: navigator.userAgent
            };
            
            this.logs.push(logEntry);
            
            // Also log to console
            if (console && console.log) {
                console.log('[SAFARI-DEBUG]', timestamp, message, data);
            }
            
            // Send to server for logging (ES5 compatible) - only if actually Safari
            if (this.isActualSafari()) {
                this.sendToServer(logEntry);
            }
        },
        
        error: function(message, error) {
            var timestamp = new Date().toISOString();
            var errorEntry = {
                time: timestamp,
                message: 'ERROR: ' + message,
                error: error ? error.toString() : null,
                stack: error && error.stack ? error.stack : null,
                userAgent: navigator.userAgent
            };
            
            this.logs.push(errorEntry);
            
            if (console && console.error) {
                console.error('[SAFARI-DEBUG]', timestamp, message, error);
            }
            
            if (this.isActualSafari()) {
                this.sendToServer(errorEntry);
            }
        },
        
        isActualSafari: function() {
            var userAgent = navigator.userAgent;
            // Check for Safari but not Chrome/Chromium (more precise detection)
            return (userAgent.indexOf('Safari') !== -1 && 
                    userAgent.indexOf('Chrome') === -1 && 
                    userAgent.indexOf('Chromium') === -1 &&
                    userAgent.indexOf('Version/') !== -1); // Safari always has Version/
        },
        
        sendToServer: function(logEntry) {
            // Only send if we have AJAX capability
            if (typeof XMLHttpRequest !== 'undefined') {
                try {
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '/wp-admin/admin-ajax.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.send('action=hvac_safari_debug&log=' + encodeURIComponent(JSON.stringify(logEntry)));
                } catch(e) {
                    // Silent fail - don't break the page
                }
            }
        },
        
        getSummary: function() {
            return {
                totalLogs: this.logs.length,
                errors: this.logs.filter(function(log) { return log.message.indexOf('ERROR:') === 0; }),
                userAgent: navigator.userAgent,
                logs: this.logs
            };
        }
    };
    
    // Make SafariDebug globally available
    window.SafariDebug = SafariDebug;
    
    // Log initial load
    SafariDebug.log('Safari Debug System Initialized', {
        url: window.location.href,
        userAgent: navigator.userAgent,
        documentReadyState: document.readyState
    });
    
    // Test basic JavaScript features
    SafariDebug.log('Testing JavaScript Features');
    
    try {
        // Test variable declarations
        var testVar = 'test';
        SafariDebug.log('✓ var declaration works');
        
        // Test function declarations  
        function testFunction() {
            return 'function test';
        }
        SafariDebug.log('✓ function declaration works', testFunction());
        
        // Test object creation
        var testObj = {
            prop: 'value',
            method: function() {
                return 'method test';
            }
        };
        SafariDebug.log('✓ object creation works', testObj.method());
        
        // Test array operations
        var testArray = [1, 2, 3];
        SafariDebug.log('✓ array creation works', testArray.length);
        
        // Test DOM access
        if (document) {
            SafariDebug.log('✓ document object available');
            if (document.getElementById) {
                SafariDebug.log('✓ getElementById available');
            }
        }
        
        // Test jQuery detection
        if (typeof jQuery !== 'undefined') {
            SafariDebug.log('✓ jQuery available', jQuery.fn.jquery);
        } else if (typeof $ !== 'undefined') {
            SafariDebug.log('✓ $ available but not jQuery');
        } else {
            SafariDebug.log('⚠ jQuery/$ not detected');
        }
        
        // Test HVAC plugin detection
        if (typeof hvac_ajax !== 'undefined') {
            SafariDebug.log('✓ HVAC AJAX object available', hvac_ajax);
        } else {
            SafariDebug.log('⚠ HVAC AJAX object not available');
        }
        
    } catch (error) {
        SafariDebug.error('JavaScript feature test failed', error);
    }
    
    // Monitor for errors
    if (window.addEventListener) {
        window.addEventListener('error', function(event) {
            SafariDebug.error('Global JavaScript Error', {
                message: event.message,
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno,
                error: event.error
            });
        });
        
        SafariDebug.log('✓ Error monitoring enabled');
    }
    
    // Monitor unhandled promise rejections (if supported)
    if (window.addEventListener && typeof Promise !== 'undefined') {
        window.addEventListener('unhandledrejection', function(event) {
            SafariDebug.error('Unhandled Promise Rejection', {
                reason: event.reason,
                promise: event.promise
            });
        });
        SafariDebug.log('✓ Promise rejection monitoring enabled');
    }
    
    // DOM Ready monitoring
    var domReadyChecks = 0;
    var maxDomChecks = 50; // 5 seconds max
    
    function checkDOMReady() {
        domReadyChecks++;
        SafariDebug.log('DOM Ready Check #' + domReadyChecks, {
            readyState: document.readyState,
            body: document.body ? 'present' : 'missing'
        });
        
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            SafariDebug.log('✓ DOM Ready State Achieved', document.readyState);
            initializePageDebug();
        } else if (domReadyChecks < maxDomChecks) {
            setTimeout(checkDOMReady, 100);
        } else {
            SafariDebug.error('DOM Ready State Never Achieved', {
                finalState: document.readyState,
                checksPerformed: domReadyChecks
            });
        }
    }
    
    function initializePageDebug() {
        SafariDebug.log('Initializing Page-Specific Debug');
        
        try {
            // Check for critical page elements
            var criticalElements = [
                'body',
                '.hvac-trainer-grid',
                '.hvac-map-container', 
                '#hvac-trainer-modal',
                '.hvac-filter-controls'
            ];
            
            for (var i = 0; i < criticalElements.length; i++) {
                var selector = criticalElements[i];
                var element = document.querySelector ? document.querySelector(selector) : null;
                
                if (element) {
                    SafariDebug.log('✓ Found critical element: ' + selector);
                } else {
                    SafariDebug.log('⚠ Missing critical element: ' + selector);
                }
            }
            
            // Check for script loading
            var scripts = document.getElementsByTagName('script');
            var hvacScripts = [];
            
            for (var j = 0; j < scripts.length; j++) {
                if (scripts[j].src && scripts[j].src.indexOf('hvac') !== -1) {
                    hvacScripts.push({
                        src: scripts[j].src,
                        loaded: scripts[j].readyState || 'unknown'
                    });
                }
            }
            
            SafariDebug.log('HVAC Scripts Found', hvacScripts);
            
            // Test MapGeo integration
            if (typeof window.hvacShowTrainerModal === 'function') {
                SafariDebug.log('✓ MapGeo integration function available');
            } else {
                SafariDebug.log('⚠ MapGeo integration function missing');
            }
            
        } catch (error) {
            SafariDebug.error('Page debug initialization failed', error);
        }
    }
    
    // Start DOM monitoring
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        initializePageDebug();
    } else {
        checkDOMReady();
    }
    
    // Create global debug function for manual testing
    window.getSafariDebugReport = function() {
        return SafariDebug.getSummary();
    };
    
    // Log completion
    SafariDebug.log('Safari Debug System Setup Complete');
    
})();