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

async function testManageEventFixes() {
    const browser = await chromium.launch({ headless: false });
    const page = await browser.newContext().then(ctx => ctx.newPage());
    
    console.log('=== Testing Manage Event Page Fixes ===\n');
    
    // Login as trainer
    console.log('1. Logging in...');
    await page.goto('https://upskill-staging.measurequick.com/training-login/');
    await page.fill('#user_login', 'ben+test44@measurequick.com');
    await page.fill('#user_pass', 'MQtrainer2024!');
    await page.locator('input[type="submit"], #wp-submit').first().click();
    
    // Wait for navigation to complete (should go to dashboard after login)
    await page.waitForURL('**/trainer/dashboard/**', { timeout: 10000 }).catch(() => {
        console.log('   - Login may have failed, continuing anyway...');
    });
    await page.waitForLoadState('networkidle');
    
    // Go to manage event page
    console.log('2. Navigating to manage event page...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
    await page.waitForLoadState('networkidle');
    
    // Wait a bit more to ensure page is fully loaded
    await page.waitForTimeout(2000);
    
    // Check if we're on the right page
    const currentURL = page.url();
    console.log('   - Current URL:', currentURL);
    if (!currentURL.includes('trainer/event/manage')) {
        console.log('   ❌ WARNING: Not on manage event page! May have been redirected.');
    }
    
    // Check for duplicate navigation
    console.log('\n3. Checking for duplicate navigation...');
    const navSections = await page.locator('.hvac-dashboard-nav').count();
    console.log(`   - Navigation sections found: ${navSections}`);
    if (navSections > 1) {
        console.log('   ❌ FAIL: Duplicate navigation detected!');
    } else {
        console.log('   ✅ PASS: No duplicate navigation');
    }
    
    // Check CSS files
    console.log('\n4. Checking CSS files...');
    const cssInfo = await page.evaluate(() => {
        const cssFiles = Array.from(document.querySelectorAll('link[rel="stylesheet"]'))
            .map(link => link.href)
            .filter(href => href.includes('hvac'));
            
        return {
            files: cssFiles.map(url => url.split('/').pop()),
            hasDashboardCSS: cssFiles.some(f => f.includes('hvac-dashboard.css')),
            hasLayoutCSS: cssFiles.some(f => f.includes('hvac-layout.css')),
            hasPageTemplatesCSS: cssFiles.some(f => f.includes('hvac-page-templates.css'))
        };
    });
    
    console.log('   - CSS files:', cssInfo.files.join(', '));
    console.log(`   - Has dashboard CSS: ${cssInfo.hasDashboardCSS ? '✅' : '❌'}`);
    console.log(`   - Has layout CSS: ${cssInfo.hasLayoutCSS ? '✅' : '❌'}`);
    console.log(`   - Has page templates CSS: ${cssInfo.hasPageTemplatesCSS ? '✅' : '❌'}`);
    
    // Check body classes
    console.log('\n5. Checking body classes...');
    const bodyClasses = await page.evaluate(() => document.body.className);
    console.log('   - Body classes:', bodyClasses);
    const hasPluginClass = bodyClasses.includes('hvac-plugin-page');
    console.log(`   - Has hvac-plugin-page class: ${hasPluginClass ? '✅' : '❌'}`);
    
    // Check layout constraints
    console.log('\n6. Checking layout constraints...');
    const layoutInfo = await page.evaluate(() => {
        const container = document.querySelector('.ast-container') || 
                         document.querySelector('.container') ||
                         document.querySelector('.site-content');
        
        if (!container) return { error: 'No container found' };
        
        const styles = window.getComputedStyle(container);
        const rect = container.getBoundingClientRect();
        
        return {
            maxWidth: styles.maxWidth,
            width: styles.width,
            actualWidth: rect.width,
            padding: styles.padding,
            boxSizing: styles.boxSizing
        };
    });
    
    console.log('   - Container max-width:', layoutInfo.maxWidth);
    console.log('   - Container width:', layoutInfo.width);
    console.log('   - Actual width:', layoutInfo.actualWidth + 'px');
    console.log('   - Padding:', layoutInfo.padding);
    console.log('   - Box sizing:', layoutInfo.boxSizing);
    
    const isWidthCorrect = layoutInfo.actualWidth <= 1200 || layoutInfo.maxWidth === '1200px';
    console.log(`   - Width constraint (≤1200px): ${isWidthCorrect ? '✅' : '❌'}`);
    
    // Check for form content
    console.log('\n7. Checking form content...');
    const hasForm = await page.locator('.tribe-community-events, .tribe-events-community').first().isVisible().catch(() => false);
    const hasContent = await page.locator('.hvac-event-manage-header').isVisible().catch(() => false);
    console.log(`   - Has event form: ${hasForm ? '✅' : '❌'}`);
    console.log(`   - Has header content: ${hasContent ? '✅' : '❌'}`);
    
    // Take screenshot
    await page.screenshot({ 
        path: 'manage-event-fixes-test.png', 
        fullPage: false 
    });
    console.log('\n8. Screenshot saved as manage-event-fixes-test.png');
    
    // Summary
    console.log('\n=== Test Summary ===');
    const allPassed = navSections <= 1 && 
                     cssInfo.hasDashboardCSS && 
                     cssInfo.hasLayoutCSS && 
                     hasPluginClass && 
                     isWidthCorrect &&
                     (hasForm || hasContent);
    
    if (allPassed) {
        console.log('✅ All tests passed!');
    } else {
        console.log('❌ Some tests failed. Please review the results above.');
    }
    
    await browser.close();
}

testManageEventFixes().catch(console.error);