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

async function testMasterTrainerSimple() {
    console.log('🔍 TESTING SIMPLIFIED MASTER TRAINER TEMPLATE');
    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 simplified template
        console.log('🔍 Testing simplified master trainer template...');
        const testUrl = 'https://upskill-staging.measurequick.com/master-trainer/edit-trainer-profile?user_id=42';
        await page.goto(testUrl);
        await page.waitForLoadState('networkidle');
        
        const simpleTestResult = await page.evaluate(() => {
            return {
                url: window.location.href,
                title: document.title,
                hasEditForm: document.querySelector('#hvac-master-profile-form') !== null,
                hasBasicFields: document.querySelectorAll('#trainer_first_name, #trainer_last_name, #trainer_display_name').length,
                hasCriticalError: document.body.innerText.includes('critical error'),
                hasProfileHeader: document.querySelector('.hvac-page-header h1') !== null,
                profileHeaderText: document.querySelector('.hvac-page-header h1')?.textContent || 'none',
                hasSaveButton: document.querySelector('button[type="submit"]') !== null,
                saveButtonText: document.querySelector('button[type="submit"]')?.textContent || 'none',
                hasFormFields: document.querySelectorAll('input, select, textarea').length,
                fieldValues: {
                    firstName: document.querySelector('#trainer_first_name')?.value || 'none',
                    lastName: document.querySelector('#trainer_last_name')?.value || 'none',
                    displayName: document.querySelector('#trainer_display_name')?.value || 'none'
                },
                hasErrorMessages: document.body.innerText.includes('must be a master trainer') || 
                                document.body.innerText.includes('User not found') ||
                                document.body.innerText.includes('Profile management system is not available') ||
                                document.body.innerText.includes('No trainer profile found'),
                contentPreview: document.body.innerText.slice(0, 400).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('📊 Simplified template test results:', simpleTestResult);
        
        if (simpleTestResult.hasEditForm && !simpleTestResult.hasCriticalError) {
            console.log('🎉 SUCCESS! Simplified template is working!');
            console.log(`   ✅ Profile header: ${simpleTestResult.profileHeaderText}`);
            console.log(`   ✅ Form fields: ${simpleTestResult.hasFormFields}`);
            console.log(`   ✅ Save button: ${simpleTestResult.saveButtonText}`);
            console.log(`   ✅ Field values: ${JSON.stringify(simpleTestResult.fieldValues)}`);
            
            // Test form interaction
            console.log('🔍 Testing form interaction...');
            
            // Try clicking the save button
            await page.click('button[type="submit"]');
            await page.waitForTimeout(3000);
            
            const formTestResult = await page.evaluate(() => {
                const messagesDiv = document.getElementById('hvac-profile-messages');
                return {
                    hasTestMessage: messagesDiv && messagesDiv.innerHTML.includes('Profile edit form is working'),
                    messageContent: messagesDiv ? messagesDiv.textContent : 'none',
                    saveButtonDisabled: document.querySelector('button[type="submit"]')?.disabled || false,
                    saveButtonText: document.querySelector('button[type="submit"]')?.textContent || 'none'
                };
            });
            
            console.log('📝 Form interaction test:', formTestResult);
            
            if (formTestResult.hasTestMessage) {
                console.log('✅ Form submission working - test message displayed!');
            }
            
            await page.screenshot({ path: 'master-trainer-simple-success.png', fullPage: true });
            
        } else if (simpleTestResult.hasCriticalError) {
            console.log('❌ Still has critical error even with simplified template');
            await page.screenshot({ path: 'master-trainer-simple-error.png', fullPage: true });
        } else if (simpleTestResult.hasErrorMessages) {
            console.log('⚠️ Has error messages but no critical error');
        } else {
            console.log('⚠️ No form found - check content preview');
        }
        
        console.log('================================================================================');
        console.log('🎯 SIMPLIFIED MASTER TRAINER TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during simplified master trainer test:', error);
        await page.screenshot({ path: 'master-trainer-simple-test-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testMasterTrainerSimple();