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

async function testMasterTrainerProfiles() {
    console.log('🔍 TESTING MASTER TRAINER PROFILE MANAGEMENT');
    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');
        
        // Check master dashboard for trainer list
        console.log('🔍 Checking master dashboard for trainer information...');
        await page.waitForLoadState('networkidle');
        
        const dashboardContent = await page.evaluate(() => {
            const trainerLinks = [...document.querySelectorAll('a[href*="trainer"], a[href*="profile"]')];
            const clickableTrainers = trainerLinks.filter(link => 
                link.textContent.includes('@') || 
                link.textContent.match(/[A-Z][a-z]+ [A-Z][a-z]+/) ||
                link.href.includes('trainer-profile')
            );
            
            return {
                totalLinks: trainerLinks.length,
                clickableTrainers: clickableTrainers.map(link => ({
                    text: link.textContent.trim(),
                    href: link.href,
                    isEmail: link.textContent.includes('@')
                })),
                hasTrainerStats: document.body.innerText.includes('trainers') || document.body.innerText.includes('Trainers'),
                statsPreview: document.body.innerText.match(/\d+\s+trainers?/gi) || []
            };
        });
        
        console.log('👥 Master dashboard trainer info:', dashboardContent);
        
        // Try to find and click on a trainer profile link
        if (dashboardContent.clickableTrainers.length > 0) {
            console.log('🔍 Testing trainer profile access from master dashboard...');
            const firstTrainer = dashboardContent.clickableTrainers[0];
            console.log(`📍 Testing link: ${firstTrainer.text} -> ${firstTrainer.href}`);
            
            await page.goto(firstTrainer.href);
            await page.waitForLoadState('networkidle');
            
            const profilePageContent = await page.evaluate(() => {
                return {
                    url: window.location.href,
                    title: document.title,
                    hasProfileContent: document.querySelector('.hvac-trainer-profile-view, .profile') !== null,
                    hasEditCapability: document.querySelector('input, select, textarea, [contenteditable]') !== null,
                    pageType: document.body.innerText.includes('Edit') ? 'edit' : 'view',
                    contentPreview: document.body.innerText.slice(0, 400).replace(/\\s+/g, ' ').trim()
                };
            });
            
            console.log('👤 Trainer profile page results:', profilePageContent);
            
            if (profilePageContent.hasProfileContent) {
                console.log('✅ Master trainer can access trainer profiles!');
            } else {
                console.log('❌ Profile content not found');
            }
            
            await page.screenshot({ path: 'master-trainer-profile-access.png', fullPage: true });
        } else {
            console.log('⚠️  No clickable trainer links found in master dashboard');
        }
        
        // Test master trainer editing capability
        console.log('🔍 Testing master trainer profile editing capabilities...');
        
        // Try to access a trainer profile edit URL directly
        const testTrainerEditUrl = 'https://upskill-staging.measurequick.com/master-trainer/trainer-profile/edit?user_id=1';
        await page.goto(testTrainerEditUrl);
        await page.waitForLoadState('networkidle');
        
        const editPageContent = await page.evaluate(() => {
            return {
                url: window.location.href,
                title: document.title,
                hasEditForm: document.querySelector('form') !== null,
                hasTrainerFields: document.querySelector('input[name*="trainer"], select[name*="trainer"]') !== null,
                isForbidden: document.body.innerText.includes('403') || document.body.innerText.includes('forbidden'),
                isNotFound: document.body.innerText.includes('404') || document.body.innerText.includes('not found'),
                pageContent: document.body.innerText.slice(0, 300).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('✏️ Master trainer edit capability:', editPageContent);
        
        await page.screenshot({ path: 'master-trainer-edit-test.png', fullPage: true });
        
        // Test access to trainer list/management
        console.log('🔍 Testing trainer management access...');
        const trainerManagementUrls = [
            'https://upskill-staging.measurequick.com/master-trainer/trainers/',
            'https://upskill-staging.measurequick.com/wp-admin/users.php?role=hvac_trainer'
        ];
        
        for (const url of trainerManagementUrls) {
            console.log(`📍 Testing: ${url}`);
            await page.goto(url);
            await page.waitForLoadState('networkidle');
            
            const pageInfo = await page.evaluate(() => {
                return {
                    title: document.title,
                    hasUserList: document.querySelector('.wp-list-table, .user-list, .trainer-list') !== null,
                    userCount: document.querySelectorAll('tr[id*="user"], .trainer-item').length,
                    accessDenied: document.body.innerText.includes('access denied') || document.body.innerText.includes('permission'),
                    isAdminArea: window.location.href.includes('wp-admin')
                };
            });
            
            console.log(`  📊 Result:`, pageInfo);
        }
        
        console.log('================================================================================');
        console.log('🎯 MASTER TRAINER PROFILE MANAGEMENT TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during master trainer profile test:', error);
        await page.screenshot({ path: 'master-trainer-profile-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testMasterTrainerProfiles();