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

async function testMasterTrainerSuccess() {
    console.log('🔍 TESTING MASTER TRAINER SUCCESS - ERROR HANDLING FIXES');
    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 URL with error handling fixes
        console.log('🔍 Testing master trainer profile edit with error handling...');
        const testUrl = 'https://upskill-staging.measurequick.com/master-trainer/edit-trainer-profile?user_id=42';
        await page.goto(testUrl);
        await page.waitForLoadState('networkidle');
        
        const finalTestResult = 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,
                hasCriticalError: document.body.innerText.includes('critical error'),
                hasPermissionError: document.body.innerText.includes('must be a master trainer'),
                hasUserNotFound: document.body.innerText.includes('User not found'),
                hasNoProfile: document.body.innerText.includes('No trainer profile found'),
                hasSystemUnavailable: document.body.innerText.includes('Profile management system is not available'),
                hasProfileHeader: document.querySelector('.hvac-page-header h1') !== null,
                profileHeaderText: document.querySelector('.hvac-page-header h1')?.textContent || 'none',
                hasFormSections: document.querySelectorAll('.hvac-form-section').length,
                formSectionTitles: [...document.querySelectorAll('.hvac-form-section h3')].map(h => h.textContent),
                hasSaveButton: document.querySelector('button[type="submit"]') !== null,
                saveButtonText: document.querySelector('button[type="submit"]')?.textContent || 'none',
                contentPreview: document.body.innerText.slice(0, 500).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('📊 Final test results:', finalTestResult);
        
        if (finalTestResult.hasEditForm) {
            console.log('🎉 COMPLETE SUCCESS! Master trainer profile edit is fully functional!');
            
            // Test specific functionality
            const functionalityTest = await page.evaluate(() => {
                const form = document.querySelector('#hvac-master-profile-form');
                if (!form) return { error: 'No form found' };
                
                return {
                    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 || 'none',
                    hasProfileIdField: document.querySelector('input[name="profile_id"]') !== null,
                    profileIdValue: document.querySelector('input[name="profile_id"]')?.value || 'none',
                    certificationFields: {
                        status: document.querySelector('#certification_status') !== null,
                        type: document.querySelector('#certification_type') !== null,
                        date: document.querySelector('#date_certified') !== null
                    },
                    personalFields: {
                        firstName: document.querySelector('#trainer_first_name') !== null,
                        lastName: document.querySelector('#trainer_last_name') !== null,
                        displayName: document.querySelector('#trainer_display_name') !== null
                    },
                    locationFields: {
                        city: document.querySelector('#trainer_city') !== null,
                        state: document.querySelector('#trainer_state') !== null,
                        country: document.querySelector('#trainer_country') !== null
                    },
                    hasAutoSaveIndicator: document.querySelector('#hvac-autosave-indicator') !== null,
                    hasUnsavedIndicator: document.querySelector('#hvac-unsaved-indicator') !== null
                };
            });
            
            console.log('⚙️ Functionality test results:', functionalityTest);
            
            if (functionalityTest.userIdValue === '42') {
                console.log('✅ Correct user data loaded (user_id=42)');
            }
            
            await page.screenshot({ path: 'master-trainer-edit-complete-success.png', fullPage: true });
            
        } else if (finalTestResult.hasCriticalError) {
            console.log('❌ Still has critical error after fixes');
        } else if (finalTestResult.hasPermissionError) {
            console.log('❌ Permission error - user may not have master trainer role');
        } else if (finalTestResult.hasNoProfile) {
            console.log('❌ No trainer profile found for user');
        } else if (finalTestResult.hasSystemUnavailable) {
            console.log('❌ Profile management system not available');
        } else {
            console.log('⚠️ Different issue - check content');
        }
        
        // Test dashboard integration
        console.log('🔍 Testing complete dashboard integration...');
        await page.goto('https://upskill-staging.measurequick.com/master-trainer/master-dashboard/');
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000); // Wait for AJAX
        
        const dashboardIntegration = await page.evaluate(() => {
            const trainerLinks = [...document.querySelectorAll('a[href*="edit-trainer-profile"]')];
            return {
                totalTrainerLinks: trainerLinks.length,
                firstThreeLinks: trainerLinks.slice(0, 3).map(link => ({
                    text: link.textContent.trim(),
                    href: link.href
                })),
                hasTrainerTable: document.querySelector('table') !== null,
                hasTrainerStats: document.body.innerText.includes('trainer') || document.body.innerText.includes('Trainer'),
                statsText: document.body.innerText.match(/\d+\s+total\s+trainers?/i) || []
            };
        });
        
        console.log('📊 Dashboard integration results:', dashboardIntegration);
        
        if (dashboardIntegration.totalTrainerLinks > 0 && finalTestResult.hasEditForm) {
            console.log('🎉 MASTER TRAINER SYSTEM IS FULLY OPERATIONAL!');
            console.log(`   ✅ ${dashboardIntegration.totalTrainerLinks} clickable trainer links in dashboard`);
            console.log(`   ✅ Profile edit form with ${finalTestResult.hasFormSections} sections`);
            console.log(`   ✅ All form fields and functionality working`);
        }
        
        console.log('================================================================================');
        console.log('🎯 MASTER TRAINER SUCCESS TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during master trainer success test:', error);
        await page.screenshot({ path: 'master-trainer-success-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testMasterTrainerSuccess();