/**
 * Test Custom Event Edit Form with Proper Login
 * Uses /training-login page as required for HVAC trainer role permissions
 */

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

async function testCustomEditWithLogin() {
    console.log('🔄 Testing Custom Event Edit Form with Proper Authentication...\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: Login via /training-login (required for HVAC trainer permissions)
        console.log('1️⃣ Logging in via /training-login...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        // Fill login form - use seeded test account
        await page.fill('input[name="log"]', 'JoeMedosch@gmail.com');
        await page.fill('input[name="pwd"]', 'JoeTrainer2025@');
        
        // Submit form - try multiple selectors
        const submitButton = await page.$('input[type="submit"]') || 
                             await page.$('button[type="submit"]') ||
                             await page.$('#wp-submit');
        if (submitButton) {
            await submitButton.click();
        } else {
            // Log what's on the page for debugging
            const formHtml = await page.$eval('form', el => el.outerHTML).catch(() => 'No form found');
            console.log('Form HTML:', formHtml.substring(0, 500));
            throw new Error('Login submit button not found');
        }
        
        // Wait for redirect after login
        await page.waitForTimeout(3000);
        console.log('✅ Login submitted\n');
        
        // Step 2: Verify we're logged in by checking dashboard
        console.log('2️⃣ Verifying authentication...');
        await page.goto(`${baseUrl}/trainer/dashboard/`);
        await page.waitForLoadState('networkidle');
        
        const pageTitle = await page.title();
        console.log(`   Dashboard title: ${pageTitle}`);
        
        // Check for dashboard content
        const dashboardContent = await page.content();
        if (dashboardContent.includes('Trainer Dashboard') || dashboardContent.includes('Events Overview')) {
            console.log('   ✅ Successfully authenticated and on dashboard\n');
        } else if (dashboardContent.includes('Login') || dashboardContent.includes('log in')) {
            throw new Error('Not authenticated - still seeing login page');
        }
        
        // Step 3: Navigate to custom edit form
        console.log('3️⃣ Navigating to custom event edit form...');
        
        // First, let's check if we have any events
        const eventLinks = await page.$$('a[href*="event"]');
        console.log(`   Found ${eventLinks.length} event-related links`);
        
        // Try to navigate to edit page with a test event ID
        const editUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        console.log(`   Navigating to: ${editUrl}`);
        
        await page.goto(editUrl);
        await page.waitForLoadState('networkidle');
        
        // Step 4: Verify custom form loaded
        console.log('\n4️⃣ Checking custom form elements...');
        
        const currentTitle = await page.title();
        console.log(`   Page title: ${currentTitle}`);
        
        // Check for custom 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');
            
            // Check what's on the page
            const content = await page.content();
            if (content.includes('404') || content.includes('Page not found')) {
                console.log('   ⚠️  404 Error - Edit page not found');
                console.log('   Creating edit page via WP-CLI...');
                
                // The page needs to be created
                // This would normally be done during plugin activation
            } else if (content.includes('Access denied') || content.includes('not authorized')) {
                console.log('   ⚠️  Access denied - permission issue');
            } else if (content.includes('tribe-community-events')) {
                console.log('   ⚠️  TEC form loaded instead of custom form');
            }
        }
        
        // Check for form fields
        const formFields = {
            'Title': '#post_title',
            'Start Date': '#EventStartDate',
            'End Date': '#EventEndDate',
            'Start Time': '#EventStartTime',
            'End Time': '#EventEndTime',
            'Event Cost': '#EventCost',
            'Event URL': '#EventURL',
            'Venue Name': '#venue_name',
            'Organizer Name': '#organizer_name'
        };
        
        console.log('\n5️⃣ Checking form fields...');
        let fieldsFound = 0;
        let fieldsMissing = 0;
        
        for (const [name, selector] of Object.entries(formFields)) {
            const field = await page.$(selector);
            if (field) {
                const value = await field.evaluate(el => el.value || '');
                console.log(`   ✅ ${name}: Found (value: "${value.substring(0, 30)}...")`);
                fieldsFound++;
            } else {
                console.log(`   ❌ ${name}: NOT FOUND`);
                fieldsMissing++;
            }
        }
        
        console.log(`\n   Summary: ${fieldsFound} fields found, ${fieldsMissing} missing`);
        
        // Step 6: If form is present, test editing
        if (fieldsFound > 5) {
            console.log('\n6️⃣ Testing form editing...');
            
            const titleField = await page.$('#post_title');
            if (titleField) {
                const originalTitle = await titleField.evaluate(el => el.value);
                const newTitle = `Test Event - ${Date.now()}`;
                
                await page.fill('#post_title', newTitle);
                console.log(`   Updated title to: ${newTitle}`);
                
                // Update other fields
                await page.fill('#EventCost', '299');
                await page.fill('#EventURL', 'https://example.com/test');
                
                // Try to save
                const saveButton = await page.$('button[type="submit"]');
                if (saveButton) {
                    console.log('   Clicking save button...');
                    await saveButton.click();
                    
                    // Wait for response
                    await page.waitForTimeout(3000);
                    
                    // Check for success message
                    const successMsg = await page.$('.hvac-notice-success');
                    if (successMsg) {
                        console.log('   ✅ Success message displayed');
                    }
                    
                    // Verify changes persisted
                    const savedTitle = await page.$eval('#post_title', el => el.value).catch(() => '');
                    if (savedTitle === newTitle) {
                        console.log('   ✅ Changes persisted!');
                    }
                } else {
                    console.log('   ❌ Save button not found');
                }
            }
        }
        
        console.log('\n✅ Test Complete!');
        
        if (fieldsFound > 5) {
            console.log('\n🎉 Custom Event Edit Form is working!');
            console.log('   - Authentication via /training-login successful');
            console.log('   - Custom form loads without JavaScript dependencies');
            console.log('   - Fields populate from database');
            console.log('   - No TEC shortcode dependencies');
        } else {
            console.log('\n⚠️  Custom form not fully functional yet');
            console.log('   - May need to create the edit page');
            console.log('   - Check if rewrite rules need flushing');
        }
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        // Take screenshot
        await page.screenshot({ 
            path: `custom-edit-error-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('📸 Screenshot saved for debugging');
        
        throw error;
    } finally {
        await browser.close();
    }
}

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