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

async function testMasterTrainerFinal() {
    console.log('🔍 TESTING MASTER TRAINER FINAL - NEW URL STRUCTURE');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as master trainer
        console.log('📝 Logging in as master trainer...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'JoeMedosch@gmail.com');
        await page.fill('#user_pass', 'JoeTrainer2025@');
        await page.click('#wp-submit');
        await page.waitForURL('**/master-trainer/master-dashboard/**', { timeout: 15000 });
        console.log('✅ Master trainer login successful');
        
        // Test the new direct URL structure
        console.log('🔍 Testing new URL structure directly...');
        const newTestUrl = 'https://upskill-staging.measurequick.com/master-trainer/edit-trainer-profile?user_id=42';
        await page.goto(newTestUrl);
        await page.waitForLoadState('networkidle');
        
        const newUrlTestResult = await page.evaluate(() => {
            return {
                url: window.location.href,
                title: document.title,
                hasEditForm: document.querySelector('#hvac-master-profile-form') !== null,
                hasTrainerFields: document.querySelectorAll('input, select, textarea').length,
                isNotFound: document.body.innerText.includes("doesn't seem to exist") || document.title.includes('not found'),
                hasProfileHeader: document.querySelector('.hvac-page-header h1') !== null,
                profileHeaderText: document.querySelector('.hvac-page-header h1')?.textContent || 'none',
                hasMasterTrainerContent: document.body.innerText.includes('master trainer') || document.body.innerText.includes('Master Trainer'),
                contentPreview: document.body.innerText.slice(0, 500).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('📊 New URL structure test results:', newUrlTestResult);
        
        if (newUrlTestResult.hasEditForm) {
            console.log('✅ NEW URL STRUCTURE WORKS! Master trainer profile edit is functional!');
            
            // Test specific form functionality
            const formAnalysis = await page.evaluate(() => {
                const form = document.querySelector('#hvac-master-profile-form');
                if (!form) return { error: 'No form found' };
                
                const sections = [...document.querySelectorAll('.hvac-form-section')];
                const sectionData = sections.map(section => {
                    const title = section.querySelector('h3')?.textContent || 'No title';
                    const fields = section.querySelectorAll('input, select, textarea').length;
                    return { title, fields };
                });
                
                return {
                    totalSections: sections.length,
                    sectionBreakdown: sectionData,
                    hasNonceField: document.querySelector('input[name="hvac_profile_nonce"]') !== null,
                    hasUserIdField: document.querySelector('input[name="edit_user_id"]') !== null,
                    userIdValue: document.querySelector('input[name="edit_user_id"]')?.value,
                    hasCertificationSection: sectionData.some(s => s.title.includes('Certification')),
                    certificationFields: document.querySelectorAll('#certification_status, #certification_type, #date_certified').length
                };
            });
            
            console.log('📝 Detailed form analysis:', formAnalysis);
            
            await page.screenshot({ path: 'master-trainer-edit-final-success.png', fullPage: true });
            
        } else if (newUrlTestResult.isNotFound) {
            console.log('❌ New URL structure still showing "not found"');
            await page.screenshot({ path: 'master-trainer-edit-still-404.png', fullPage: true });
        } else {
            console.log('⚠️ Unknown issue - check content');
            await page.screenshot({ path: 'master-trainer-edit-unknown-issue.png', fullPage: true });
        }
        
        // Test the updated dashboard links
        console.log('🔍 Testing updated dashboard links...');
        await page.goto('https://upskill-staging.measurequick.com/master-trainer/master-dashboard/');
        await page.waitForLoadState('networkidle');
        
        // Wait for the AJAX data to load
        await page.waitForTimeout(3000);
        
        const dashboardLinks = await page.evaluate(() => {
            // Look for the new URL pattern
            const newLinks = [...document.querySelectorAll('a[href*="edit-trainer-profile"]')];
            return newLinks.slice(0, 3).map(link => ({
                text: link.textContent.trim(),
                href: link.href
            }));
        });
        
        console.log('🔗 Updated dashboard links:', dashboardLinks);
        
        if (dashboardLinks.length > 0) {
            console.log(`🔍 Testing updated dashboard link: ${dashboardLinks[0].text}`);
            await page.goto(dashboardLinks[0].href);
            await page.waitForLoadState('networkidle');
            
            const dashboardLinkTest = await page.evaluate(() => {
                return {
                    url: window.location.href,
                    title: document.title,
                    hasEditForm: document.querySelector('#hvac-master-profile-form') !== null,
                    hasTrainerName: document.querySelector('.hvac-page-header h1')?.textContent || 'none',
                    isWorking: document.querySelector('#hvac-master-profile-form') !== null
                };
            });
            
            console.log('🎯 Dashboard link test result:', dashboardLinkTest);
            
            if (dashboardLinkTest.isWorking) {
                console.log('✅ COMPLETE SUCCESS! Master trainer dashboard links are working!');
            }
            
            await page.screenshot({ path: 'master-trainer-dashboard-link-final.png', fullPage: true });
        } else {
            console.log('⚠️ No updated links found in dashboard - may need to clear cache');
        }
        
        console.log('================================================================================');
        console.log('🎯 MASTER TRAINER FINAL TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during master trainer final test:', error);
        await page.screenshot({ path: 'master-trainer-final-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testMasterTrainerFinal();