const { webkit } = require('playwright');

(async () => {
    console.log('🧪 Testing Safari compatibility fix with comprehensive resource monitoring...');
    
    const browser = await webkit.launch({
        headless: true // headless to avoid display issues
    });

    const context = await browser.newContext({
        // Simulate Safari browser exactly as it would appear
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15'
    });
    
    const page = await context.newPage();
    
    // Track console messages and errors
    const consoleMessages = [];
    const pageErrors = [];
    
    page.on('console', msg => {
        const message = `[${msg.type().toUpperCase()}] ${msg.text()}`;
        console.log(message);
        consoleMessages.push(message);
    });
    
    page.on('pageerror', error => {
        const errorMsg = `[PAGE ERROR] ${error.message}`;
        console.log(errorMsg);
        pageErrors.push(errorMsg);
    });
    
    page.on('response', response => {
        if (response.url().includes('.css') || response.url().includes('.js')) {
            console.log(`📄 Resource: ${response.status()} - ${response.url()}`);
        }
    });
    
    console.log('📍 Navigating to find-a-trainer page with Safari user agent...');
    try {
        await page.goto('https://upskill-staging.measurequick.com/find-a-trainer/', { 
            waitUntil: 'networkidle',
            timeout: 30000 
        });
        console.log('✅ Page loaded successfully');
    } catch (error) {
        console.log('⚠️ Page load error:', error.message);
    }
    
    console.log('⏳ Waiting for Safari Script Blocker to initialize...');
    await page.waitForTimeout(3000);
    
    // Check Safari Script Blocker activation
    console.log('🛡️ Checking Safari Script Blocker activation...');
    const safariBlockerStatus = await page.evaluate(() => {
        // Look for Safari blocker console messages
        const scriptTags = Array.from(document.querySelectorAll('script'));
        const hasBlockerScript = scriptTags.some(script => 
            script.innerHTML.includes('Safari Script Protection System') ||
            script.innerHTML.includes('Safari Script Blocker activated')
        );
        
        return {
            hasBlockerScript: hasBlockerScript,
            totalScripts: scriptTags.length,
            scriptsWithSrc: scriptTags.filter(s => s.src).length,
            bodyExists: !!document.body,
            hasContent: document.body ? document.body.innerHTML.length > 1000 : false,
            readyState: document.readyState,
            url: window.location.href
        };
    });
    
    console.log('📊 Safari Script Blocker Status:', safariBlockerStatus);
    
    // Check resource loading - should be minimal for Safari
    console.log('🔍 Analyzing resource loading for Safari compatibility...');
    const resourceAnalysis = await page.evaluate(() => {
        const allLinks = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
        const allScripts = Array.from(document.querySelectorAll('script[src]'));
        
        const cssFiles = allLinks.map(link => ({
            href: link.href,
            isHVAC: link.href.includes('hvac'),
            isSafariCompatible: link.href.includes('safari') || link.href.includes('minimal')
        }));
        
        const jsFiles = allScripts.map(script => ({
            src: script.src,
            isHVAC: script.src.includes('hvac'),
            isSafariCompatible: script.src.includes('safari-compatible')
        }));
        
        return {
            totalCSSFiles: cssFiles.length,
            hvacCSSFiles: cssFiles.filter(f => f.isHVAC),
            totalJSFiles: jsFiles.length,
            hvacJSFiles: jsFiles.filter(f => f.isHVAC),
            safariCompatibleJS: jsFiles.filter(f => f.isSafariCompatible)
        };
    });
    
    console.log('📈 Resource Analysis:', resourceAnalysis);
    
    // Test specific Safari fix indicators
    console.log('🔍 Testing Safari-specific fixes...');
    const safariFixStatus = await page.evaluate(() => {
        return {
            safariMinimalMode: typeof window.HVAC_SAFARI_MINIMAL_MODE !== 'undefined',
            safariScriptBlocker: typeof window.hvacSafariScriptBlocker !== 'undefined',
            hasMapGeo: typeof window.MapGeoWidget !== 'undefined',
            hasJQuery: typeof window.jQuery !== 'undefined',
            documentTitle: document.title,
            pageHasTrainerCards: document.querySelectorAll('.hvac-trainer-card').length > 0,
            pageHasMap: document.querySelectorAll('[id*="map"]').length > 0
        };
    });
    
    console.log('🎯 Safari Fix Status:', safariFixStatus);
    
    // Test page functionality if content loaded
    if (safariBlockerStatus.hasContent) {
        console.log('🧪 Testing page functionality...');
        try {
            // Check if trainer cards are present and functional
            const trainerCards = await page.$$('.hvac-trainer-card');
            console.log(`👥 Found ${trainerCards.length} trainer cards`);
            
            // Test if interactive elements work
            const interactiveTest = await page.evaluate(() => {
                return {
                    hasModals: document.querySelectorAll('[id*="modal"]').length,
                    hasButtons: document.querySelectorAll('button, .btn').length,
                    hasTrainerCards: document.querySelectorAll('.hvac-trainer-card').length,
                    hasContactForm: document.querySelectorAll('form').length,
                    canAccessDOM: !!document.getElementById || !!document.querySelector
                };
            });
            
            console.log('⚙️ Interactive Elements Test:', interactiveTest);
            
            // Test if page content is actually rendered
            const contentCheck = await page.evaluate(() => {
                const bodyText = document.body ? document.body.textContent : '';
                return {
                    bodyTextLength: bodyText.length,
                    hasTrainerText: bodyText.includes('trainer') || bodyText.includes('HVAC'),
                    hasLoadingText: bodyText.includes('Loading'),
                    visibleElements: document.querySelectorAll('*:not([style*="display: none"])').length
                };
            });
            
            console.log('📝 Content Check:', contentCheck);
            
        } catch (error) {
            console.log('❌ Error testing functionality:', error.message);
        }
    }
    
    // Summary
    console.log('\n🎉 Safari Compatibility Test Summary:');
    console.log(`🛡️ Safari Script Blocker: ${safariBlockerStatus.hasBlockerScript ? 'ACTIVE' : 'NOT FOUND'}`);
    console.log(`📄 Page Loaded: ${safariBlockerStatus.hasContent ? 'SUCCESS' : 'FAILED'}`);
    console.log(`📊 Total CSS Files: ${resourceAnalysis.totalCSSFiles} (HVAC: ${resourceAnalysis.hvacCSSFiles.length})`);
    console.log(`📊 Total JS Files: ${resourceAnalysis.totalJSFiles} (HVAC: ${resourceAnalysis.hvacJSFiles.length})`);
    console.log(`🔧 Safari Minimal Mode: ${safariFixStatus.safariMinimalMode ? 'ACTIVE' : 'NOT ACTIVE'}`);
    console.log(`🎯 Page Functionality: ${safariBlockerStatus.hasContent && safariFixStatus.hasJQuery ? 'WORKING' : 'LIMITED'}`);
    console.log(`📱 Console Messages: ${consoleMessages.length}`);
    console.log(`❌ Page Errors: ${pageErrors.length}`);
    
    if (pageErrors.length === 0 && safariBlockerStatus.hasContent) {
        console.log('\n✅ SAFARI COMPATIBILITY FIX APPEARS SUCCESSFUL!');
        console.log('✅ No critical errors detected');
        console.log('✅ Page content loaded properly');
        console.log('✅ Safari Script Blocker active');
    } else {
        console.log('\n⚠️ Issues detected:');
        if (pageErrors.length > 0) {
            console.log('❌ Page errors found:', pageErrors);
        }
        if (!safariBlockerStatus.hasContent) {
            console.log('❌ Page content did not load properly');
        }
    }
    
    await browser.close();
})();