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

async function testProfileFixes() {
    console.log('🔍 TESTING PROFILE SYSTEM FIXES POST-DEPLOYMENT');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as test trainer
        console.log('📝 Logging in as test trainer...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForURL('**/trainer/dashboard/**', { timeout: 15000 });
        console.log('✅ Login successful');
        
        // Test profile view page
        console.log('🔍 Testing profile view page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/profile/');
        await page.waitForLoadState('networkidle');
        
        const profileContent = await page.evaluate(() => {
            return {
                hasProfileView: document.querySelector('.hvac-trainer-profile-view') !== null,
                hasPageHeader: document.querySelector('.hvac-page-header') !== null,
                hasEditButton: document.querySelector('a[href*="edit"]') !== null,
                hasProfileSections: document.querySelectorAll('.hvac-profile-section').length,
                hasPlaceholderText: document.body.innerText.includes('Updated template will handle display'),
                contentPreview: document.body.innerText.slice(200, 500).replace(/\\s+/g, ' ').trim()
            };
        });
        
        console.log('📊 Profile view results:', profileContent);
        
        if (profileContent.hasProfileView) {
            console.log('✅ Profile view shortcode is now rendering content!');
        } else if (profileContent.hasPlaceholderText) {
            console.log('❌ Still showing placeholder text');
        } else {
            console.log('⚠️ Different content, need to investigate');
        }
        
        await page.screenshot({ path: 'profile-view-post-fix.png', fullPage: true });
        
        // Test profile edit page  
        console.log('🔍 Testing profile edit page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/profile/edit/');
        await page.waitForLoadState('networkidle');
        
        const editContent = await page.evaluate(() => {
            return {
                hasEditForm: document.querySelector('form') !== null,
                hasFormFields: document.querySelectorAll('input, select, textarea').length,
                hasSaveButton: document.querySelector('button[type="submit"], input[type="submit"]') !== null,
                hasPlaceholderText: document.body.innerText.includes('Updated template will handle editing'),
                formPreview: document.querySelector('form') ? 
                    document.querySelector('form').innerText.slice(0, 300).replace(/\\s+/g, ' ').trim() : 'No form found'
            };
        });
        
        console.log('📊 Profile edit results:', editContent);
        
        if (editContent.hasEditForm && editContent.hasFormFields > 0) {
            console.log('✅ Profile edit form is now working!');
        } else if (editContent.hasPlaceholderText) {
            console.log('❌ Still showing placeholder text');
        } else {
            console.log('⚠️ Different content, need to investigate');
        }
        
        await page.screenshot({ path: 'profile-edit-post-fix.png', fullPage: true });
        
        // Test profile data display
        if (profileContent.hasProfileView) {
            console.log('🔍 Testing profile data display...');
            await page.goto('https://upskill-staging.measurequick.com/trainer/profile/');
            await page.waitForLoadState('networkidle');
            
            const profileData = await page.evaluate(() => {
                const nameElement = document.querySelector('.hvac-detail-value');
                const emailElement = document.evaluate(
                    "//span[contains(@class, 'hvac-detail-value') and contains(text(), '@')]", 
                    document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null
                ).singleNodeValue;
                
                return {
                    hasName: nameElement !== null,
                    hasEmail: emailElement !== null,
                    nameText: nameElement ? nameElement.textContent : 'none',
                    emailText: emailElement ? emailElement.textContent : 'none',
                    visibleSections: [...document.querySelectorAll('.hvac-profile-section h2')].map(h => h.textContent)
                };
            });
            
            console.log('👤 Profile data display:', profileData);
        }
        
        console.log('================================================================================');
        console.log('🎯 PROFILE FIXES TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during profile fixes test:', error);
        await page.screenshot({ path: 'profile-fixes-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testProfileFixes();