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

async function comprehensiveNavigationTest() {
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();

    const testResults = [];

    // Test pages to check
    const testPages = [
        { name: 'Dashboard', url: '/trainer/dashboard/' },
        { name: 'Certificate Reports', url: '/trainer/certificate-reports/' },
        { name: 'Generate Certificates', url: '/trainer/generate-certificates/' },
        { name: 'Event Manage', url: '/trainer/event/manage/' },
        { name: 'Venue List', url: '/trainer/venue/list/' },
        { name: 'Venue Manage', url: '/trainer/venue/manage/' },
        { name: 'Organizer List', url: '/trainer/organizer/list/' },
        { name: 'Organizer Manage', url: '/trainer/organizer/manage/' },
        { name: 'Profile View', url: '/trainer/profile/' },
        { name: 'Profile Edit', url: '/trainer/profile/edit/' },
    ];

    try {
        console.log('🔐 Logging in as test_trainer...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        
        // Fill login form  
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('button[type="submit"]');
        
        // Wait for dashboard
        await page.waitForTimeout(3000);
        
        console.log('🧪 Testing all trainer pages...\n');

        for (const testPage of testPages) {
            console.log(`📄 Testing ${testPage.name}...`);
            
            try {
                await page.goto(`https://upskill-staging.measurequick.com${testPage.url}`);
                await page.waitForTimeout(2000);
                
                // Check for new WordPress menu
                const newMenuExists = await page.locator('.hvac-trainer-menu-wrapper').count() > 0;
                
                // Check for old navigation elements
                const oldNavigationMenu = await page.locator('text="NAVIGATION MENU"').count();
                const oldGreenButtons = await page.locator('.ast-button:has-text("DASHBOARD"), .ast-button:has-text("GENERATE CERTIFICATES"), .ast-button:has-text("CREATE EVENT")').count();
                
                // Check for specific old navigation patterns
                const navigationMenuDropdown = await page.locator('.ast-button:has-text("NAVIGATION MENU")').count();
                const greenNavButtons = await page.locator('.ast-button.ast-button-secondary:has-text("Dashboard"), .ast-button.ast-button-secondary:has-text("Generate Certificates")').count();
                
                // Check for page content (not blank)
                const hasContent = await page.locator('body').innerText();
                const isBlank = hasContent.trim().length < 100;
                
                // Check for errors
                const hasError = await page.locator('text="Error", text="404", text="Not Found"').count() > 0;
                
                const result = {
                    page: testPage.name,
                    url: testPage.url,
                    newMenuExists,
                    oldNavigationMenu,
                    oldGreenButtons,
                    navigationMenuDropdown,
                    greenNavButtons,
                    isBlank,
                    hasError,
                    status: 'tested'
                };
                
                // Determine overall status
                if (hasError) {
                    result.status = '❌ ERROR';
                } else if (isBlank) {
                    result.status = '⚪ BLANK';
                } else if (oldNavigationMenu > 0 || navigationMenuDropdown > 0 || greenNavButtons > 0) {
                    result.status = '🔶 HYBRID NAV';
                } else if (!newMenuExists) {
                    result.status = '❓ NO MENU';
                } else {
                    result.status = '✅ FIXED';
                }
                
                testResults.push(result);
                
                console.log(`   Status: ${result.status}`);
                console.log(`   New menu: ${newMenuExists ? '✓' : '✗'}`);
                console.log(`   Old nav elements: ${oldNavigationMenu + navigationMenuDropdown + greenNavButtons}`);
                
                // Take screenshot if there are issues
                if (result.status !== '✅ FIXED') {
                    await page.screenshot({
                        path: `issue-${testPage.name.toLowerCase().replace(/\s+/g, '-')}.png`,
                        fullPage: true
                    });
                    console.log(`   📸 Screenshot saved for ${testPage.name}`);
                }
                
            } catch (error) {
                testResults.push({
                    page: testPage.name,
                    url: testPage.url,
                    status: '❌ ERROR',
                    error: error.message
                });
                console.log(`   Status: ❌ ERROR - ${error.message}`);
            }
            
            console.log('');
        }
        
        // Generate summary report
        console.log('🎯 COMPREHENSIVE TEST RESULTS:');
        console.log('=====================================');
        
        const fixed = testResults.filter(r => r.status === '✅ FIXED').length;
        const hybridNav = testResults.filter(r => r.status === '🔶 HYBRID NAV').length;
        const blank = testResults.filter(r => r.status === '⚪ BLANK').length;
        const errors = testResults.filter(r => r.status === '❌ ERROR').length;
        const noMenu = testResults.filter(r => r.status === '❓ NO MENU').length;
        
        console.log(`✅ Fixed: ${fixed}/${testPages.length}`);
        console.log(`🔶 Hybrid Navigation: ${hybridNav}`);
        console.log(`⚪ Blank Pages: ${blank}`);
        console.log(`❌ Errors: ${errors}`);
        console.log(`❓ No Menu: ${noMenu}`);
        console.log('');
        
        // Detail issues that need fixing
        const issuePages = testResults.filter(r => r.status !== '✅ FIXED');
        if (issuePages.length > 0) {
            console.log('🔧 PAGES NEEDING FIXES:');
            issuePages.forEach(page => {
                console.log(`   ${page.status} ${page.page} (${page.url})`);
            });
        }
        
    } catch (error) {
        console.error('❌ Test Error:', error.message);
        await page.screenshot({
            path: 'comprehensive-test-error.png',
            fullPage: true
        });
    } finally {
        await browser.close();
    }
}

comprehensiveNavigationTest();