/**
 * Test Custom Event Edit with Better Login Debugging
 */

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

async function testLoginAndEdit() {
    console.log('🔄 Testing Login and Custom Event Edit Form...\n');
    
    const browser = await chromium.launch({
        headless: false,
        args: ['--disable-dev-shm-usage', '--no-sandbox']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1280, height: 720 }
    });
    
    const page = await context.newPage();
    const baseUrl = process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com';
    
    try {
        // Step 1: Navigate to login page
        console.log('1️⃣ Navigating to login page...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        // Check if we see the login form
        const loginForm = await page.$('form#hvac_community_loginform');
        if (loginForm) {
            console.log('✅ Login form found');
        } else {
            console.log('❌ Login form not found');
            const forms = await page.$$('form');
            console.log(`   Found ${forms.length} form(s) on page`);
        }
        
        // Step 2: Fill and submit login
        console.log('\n2️⃣ Filling login credentials...');
        
        // Try different selectors for username field
        const usernameField = await page.$('input[name="log"]') || 
                              await page.$('input#user_login') ||
                              await page.$('input[name="username"]');
        
        if (usernameField) {
            await usernameField.fill('test_trainer');
            console.log('   ✅ Username filled');
        } else {
            console.log('   ❌ Username field not found');
        }
        
        // Try different selectors for password field
        const passwordField = await page.$('input[name="pwd"]') || 
                              await page.$('input#user_pass') ||
                              await page.$('input[name="password"]');
        
        if (passwordField) {
            await passwordField.fill('TestTrainer123!');
            console.log('   ✅ Password filled');
        } else {
            console.log('   ❌ Password field not found');
        }
        
        // Take screenshot before submitting
        await page.screenshot({ 
            path: 'login-form-filled.png',
            fullPage: false 
        });
        console.log('   📸 Screenshot saved: login-form-filled.png');
        
        // Submit the form
        console.log('\n3️⃣ Submitting login form...');
        
        // Try multiple submit methods
        const submitButton = await page.$('input[type="submit"]') || 
                             await page.$('button[type="submit"]') ||
                             await page.$('#wp-submit');
        
        if (submitButton) {
            await Promise.all([
                page.waitForNavigation({ waitUntil: 'networkidle' }),
                submitButton.click()
            ]);
            console.log('   ✅ Form submitted and navigation completed');
        } else {
            console.log('   ❌ Submit button not found');
        }
        
        // Step 4: Check where we ended up
        console.log('\n4️⃣ Checking authentication result...');
        const currentUrl = page.url();
        const currentTitle = await page.title();
        
        console.log(`   Current URL: ${currentUrl}`);
        console.log(`   Page Title: ${currentTitle}`);
        
        // Check for login errors
        const loginError = await page.$('.login-error') || 
                          await page.$('.hvac-login-error') ||
                          await page.$('#login_error');
        
        if (loginError) {
            const errorText = await loginError.textContent();
            console.log(`   ❌ Login error: ${errorText}`);
        }
        
        // Check if we're on the dashboard
        if (currentUrl.includes('/dashboard/')) {
            console.log('   ✅ Successfully redirected to dashboard!');
        } else if (currentUrl.includes('/training-login/')) {
            console.log('   ⚠️ Still on login page - authentication may have failed');
        }
        
        // Step 5: Try navigating to edit page
        console.log('\n5️⃣ Navigating to event edit page...');
        const editUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        await page.goto(editUrl);
        await page.waitForLoadState('networkidle');
        
        const editPageUrl = page.url();
        const editPageTitle = await page.title();
        
        console.log(`   Current URL: ${editPageUrl}`);
        console.log(`   Page Title: ${editPageTitle}`);
        
        // Check if we were redirected back to login
        if (editPageUrl.includes('/training-login/')) {
            console.log('   ❌ Redirected to login - not authenticated');
        } else if (editPageUrl.includes('/trainer/event/edit/')) {
            console.log('   ✅ On edit page!');
            
            // Check for custom template marker
            const pageContent = await page.content();
            if (pageContent.includes('Custom Event Edit Template Loaded Successfully')) {
                console.log('   ✅ Custom template is loading!');
            } else {
                console.log('   ⚠️ Custom template marker not found');
            }
            
            // Check for form wrapper
            const formWrapper = await page.$('.hvac-event-edit-wrapper');
            if (formWrapper) {
                console.log('   ✅ Custom form wrapper found');
            } else {
                console.log('   ❌ Custom form wrapper NOT found');
            }
        }
        
        // Take final screenshot
        await page.screenshot({ 
            path: `final-page-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('\n📸 Final screenshot saved');
        
        console.log('\n✅ Test Complete!');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        await page.screenshot({ 
            path: `error-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('📸 Error screenshot saved');
        
        throw error;
    } finally {
        // Keep browser open for manual inspection
        console.log('\n⏸️  Keeping browser open for 10 seconds...');
        await page.waitForTimeout(10000);
        await browser.close();
    }
}

// Run test
testLoginAndEdit()
    .then(() => {
        console.log('\n✨ Test completed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n💥 Test failed:', error);
        process.exit(1);
    });