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

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

    const context = await browser.newContext({
        // Simulate Safari browser
        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
    page.on('console', msg => {
        console.log(`[${msg.type().toUpperCase()}] ${msg.text()}`);
    });
    
    page.on('pageerror', error => {
        console.log(`[PAGE ERROR] ${error.message}`);
    });
    
    console.log('📍 Navigating to find-a-trainer page...');
    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);
        
        // Try to get current page state even if navigation failed
        try {
            const currentUrl = await page.url();
            console.log('📍 Current URL:', currentUrl);
        } catch (e) {
            console.log('❌ Could not get page URL');
        }
    }
    
    console.log('⏳ Waiting for page to stabilize...');
    await page.waitForTimeout(3000);
    
    // Get comprehensive browser state
    console.log('🔍 Analyzing browser state...');
    const pageState = await page.evaluate(() => {
        return {
            url: window.location.href,
            title: document.title,
            readyState: document.readyState,
            scriptsLoaded: Array.from(document.querySelectorAll('script')).length,
            safariScriptBlocker: window.hvacSafariScriptBlocker ? 'active' : 'not found',
            hvacErrors: window.hvacErrors || [],
            bodyExists: !!document.body,
            hasContent: document.body ? document.body.innerHTML.length > 1000 : false
        };
    });
    
    console.log('📊 Page state:', pageState);
    
    // Check Safari-specific scripts
    console.log('🔍 Checking Safari script loading...');
    const allScripts = await page.evaluate(() => {
        return Array.from(document.querySelectorAll('script[src]'))
            .map(script => ({
                src: script.src,
                isSafariCompatible: script.src.includes('safari-compatible'),
                isHVAC: script.src.includes('hvac') || script.src.includes('find-trainer')
            }));
    });
    
    console.log('📄 All scripts:', allScripts.length);
    const hvacScripts = allScripts.filter(s => s.isHVAC);
    const safariScripts = allScripts.filter(s => s.isSafariCompatible);
    
    console.log('🎯 HVAC scripts:', hvacScripts);
    console.log('✅ Safari-compatible scripts:', safariScripts);
    
    // Test basic page functionality if content loaded
    if (pageState.hasContent) {
        console.log('🧪 Testing page functionality...');
        try {
            // Check if trainer cards exist
            const trainerCards = await page.$$('.hvac-trainer-card');
            console.log(`👥 Found ${trainerCards.length} trainer cards`);
            
            // Test if interactive elements are present
            const interactiveElements = await page.evaluate(() => {
                return {
                    modals: document.querySelectorAll('[id*="modal"]').length,
                    buttons: document.querySelectorAll('button, .btn').length,
                    forms: document.querySelectorAll('form').length,
                    maps: document.querySelectorAll('[id*="map"]').length
                };
            });
            
            console.log('🎯 Interactive elements:', interactiveElements);
            
        } catch (error) {
            console.log('❌ Error testing functionality:', error.message);
        }
    }
    
    console.log('🎉 Safari compatibility test completed');
    await browser.close();
})();