/**
 * Direct test of custom event edit form
 * Tests by navigating directly to a known event edit URL
 */

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

async function testCustomFormDirect() {
    console.log('🔄 Testing Custom Event Edit Form (Direct Access)...\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
        console.log('1️⃣ Logging in...');
        await page.goto(`${baseUrl}/wp-login.php`);
        await page.fill('#user_login', 'test_admin');
        await page.fill('#user_pass', 'TestAdmin123!');
        await page.click('#wp-submit');
        
        // Wait for login to complete
        await page.waitForTimeout(3000);
        console.log('✅ Login submitted\n');
        
        // Step 2: Navigate directly to edit page for a known event
        // Using event ID 6161 from the previous tests
        console.log('2️⃣ Navigating directly to edit form...');
        const editUrl = `${baseUrl}/trainer/event/edit/?event_id=6161`;
        console.log(`   URL: ${editUrl}`);
        
        await page.goto(editUrl);
        await page.waitForLoadState('networkidle');
        
        // Step 3: Check what loaded
        console.log('3️⃣ Checking page content...\n');
        
        const pageTitle = await page.title();
        console.log(`   Page Title: ${pageTitle}`);
        
        // Check for custom form
        const customForm = await page.$('.hvac-event-edit-wrapper');
        if (customForm) {
            console.log('   ✅ Custom form wrapper found');
        } else {
            console.log('   ❌ Custom form wrapper NOT found');
        }
        
        // Check for form element
        const formElement = await page.$('form.hvac-event-form');
        if (formElement) {
            console.log('   ✅ Form element found');
        } else {
            console.log('   ❌ Form element NOT found');
        }
        
        // Check for TEC elements (should NOT be present)
        const tecForm = await page.$('.tribe-community-events');
        if (tecForm) {
            console.log('   ⚠️  TEC form detected (should not be present)');
        } else {
            console.log('   ✅ No TEC dependencies found');
        }
        
        // Step 4: Check critical fields
        console.log('\n4️⃣ Checking form fields...\n');
        
        const fields = [
            { name: 'Title', selector: '#post_title' },
            { name: 'Start Date', selector: '#EventStartDate' },
            { name: 'End Date', selector: '#EventEndDate' },
            { name: 'Event Cost', selector: '#EventCost' },
            { name: 'Venue Dropdown', selector: '#venue_id' },
            { name: 'Organizer Dropdown', selector: '#organizer_id' }
        ];
        
        for (const field of fields) {
            const element = await page.$(field.selector);
            if (element) {
                const value = await element.evaluate(el => el.value || '');
                console.log(`   ✅ ${field.name}: Found (value: "${value.substring(0, 30)}${value.length > 30 ? '...' : ''}")`);
            } else {
                console.log(`   ❌ ${field.name}: NOT FOUND`);
            }
        }
        
        // Step 5: Test saving
        console.log('\n5️⃣ Testing form submission...\n');
        
        const titleField = await page.$('#post_title');
        if (titleField) {
            const currentTitle = await titleField.evaluate(el => el.value);
            const newTitle = `${currentTitle} - Test ${Date.now()}`;
            
            await page.fill('#post_title', newTitle);
            console.log(`   Updated title to: ${newTitle}`);
            
            // Find and click save button
            const saveButton = await page.$('button[type="submit"]');
            if (saveButton) {
                console.log('   Clicking save button...');
                await saveButton.click();
                
                // Wait for save
                await page.waitForTimeout(3000);
                
                // Check for success
                const successMsg = await page.$('.hvac-notice-success');
                if (successMsg) {
                    console.log('   ✅ Success message displayed!');
                } else {
                    console.log('   ⚠️  No success message found');
                }
                
                // Check if title persisted
                const savedTitle = await page.$eval('#post_title', el => el.value).catch(() => '');
                if (savedTitle === newTitle) {
                    console.log('   ✅ Title change persisted!');
                } else {
                    console.log('   ❌ Title did not persist');
                }
            } else {
                console.log('   ❌ Save button not found');
            }
        }
        
        console.log('\n✅ Test Complete!');
        
    } catch (error) {
        console.error('\n❌ Test failed:', error.message);
        
        // Take screenshot
        await page.screenshot({ 
            path: `custom-form-error-${Date.now()}.png`,
            fullPage: true 
        });
        console.log('📸 Screenshot saved');
        
        // Get page content for debugging
        const content = await page.content();
        if (content.includes('404') || content.includes('Not Found')) {
            console.log('⚠️  Page returned 404 - form page may not exist');
        }
        if (content.includes('Access Denied') || content.includes('not authorized')) {
            console.log('⚠️  Access denied - check user permissions');
        }
        
        throw error;
    } finally {
        await browser.close();
    }
}

// Run test
testCustomFormDirect()
    .then(() => {
        console.log('\n🎉 Direct test passed!');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n💥 Direct test failed:', error);
        process.exit(1);
    });