/**
 * TEC Form Inspector - Analyze TEC Community Events forms to identify correct field selectors
 */

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

async function inspectTECForm() {
    const browser = await chromium.launch({ headless: true });
    const page = await browser.newPage();
    
    try {
        // Login first
        await page.goto('https://upskill-staging.measurequick.com/trainer/training-login/');
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        // Navigate to TEC form
        await page.goto('https://upskill-staging.measurequick.com/events/network/add/');
        await page.waitForLoadState('networkidle');
        
        // Analyze all forms on the page
        const formAnalysis = await page.evaluate(() => {
            const forms = document.querySelectorAll('form');
            const analysis = {};
            
            forms.forEach((form, index) => {
                analysis[`form_${index}`] = {
                    id: form.id || `unnamed_form_${index}`,
                    action: form.action || 'no-action',
                    method: form.method || 'get',
                    fields: {}
                };
                
                // Analyze input fields
                const inputs = form.querySelectorAll('input, textarea, select');
                inputs.forEach((input) => {
                    const fieldInfo = {
                        type: input.type || (input.tagName ? input.tagName.toLowerCase() : 'unknown'),
                        name: input.name || 'no-name',
                        id: input.id || 'no-id',
                        required: input.required || (input.classList && input.classList.contains('required')),
                        placeholder: input.placeholder || 'no-placeholder',
                        visible: input.offsetWidth > 0 && input.offsetHeight > 0,
                        selector: input.id ? `#${input.id}` : (input.name ? `[name="${input.name}"]` : (input.tagName ? input.tagName.toLowerCase() : 'unknown'))
                    };
                    
                    // Try to identify common field types
                    const name = input.name || '';
                    const id = input.id || '';
                    const placeholder = (input.placeholder || '').toLowerCase();
                    
                    if (name.includes('title') || id.includes('title') || placeholder.includes('title')) {
                        analysis[`form_${index}`].fields.title = fieldInfo;
                    } else if (name.includes('content') || id.includes('content') || placeholder.includes('description')) {
                        analysis[`form_${index}`].fields.description = fieldInfo;
                    } else if (name.includes('StartDate') || id.includes('StartDate')) {
                        analysis[`form_${index}`].fields.startDate = fieldInfo;
                    } else if (name.includes('StartTime') || id.includes('StartTime')) {
                        analysis[`form_${index}`].fields.startTime = fieldInfo;
                    } else if (name.includes('EndDate') || id.includes('EndDate')) {
                        analysis[`form_${index}`].fields.endDate = fieldInfo;
                    } else if (name.includes('EndTime') || id.includes('EndTime')) {
                        analysis[`form_${index}`].fields.endTime = fieldInfo;
                    } else if (name.includes('Cost') || id.includes('Cost')) {
                        analysis[`form_${index}`].fields.cost = fieldInfo;
                    } else if (name.includes('venue') || id.includes('venue')) {
                        analysis[`form_${index}`].fields.venue = fieldInfo;
                    } else if (name.includes('organizer') || id.includes('organizer')) {
                        analysis[`form_${index}`].fields.organizer = fieldInfo;
                    } else if (input.type === 'submit') {
                        analysis[`form_${index}`].fields.submit = fieldInfo;
                    }
                });
            });
            
            return analysis;
        });
        
        console.log('📋 TEC FORM ANALYSIS');
        console.log('═'.repeat(50));
        console.log(JSON.stringify(formAnalysis, null, 2));
        
        // Find which form is the main event creation form
        const mainForm = Object.entries(formAnalysis).find(([key, form]) => 
            form.fields.title && form.fields.description && form.fields.submit
        );
        
        if (mainForm) {
            console.log('\n🎯 MAIN EVENT CREATION FORM IDENTIFIED:');
            console.log(`Form ID: ${mainForm[1].id}`);
            console.log(`Title Field: ${mainForm[1].fields.title?.selector}`);
            console.log(`Description Field: ${mainForm[1].fields.description?.selector}`);
            console.log(`Submit Button: ${mainForm[1].fields.submit?.selector}`);
            
            // Test filling out the main form
            if (mainForm[1].fields.title) {
                await page.fill(mainForm[1].fields.title.selector, 'Test Event Title');
                console.log('✅ Title field filled successfully');
            }
            
            if (mainForm[1].fields.description) {
                await page.fill(mainForm[1].fields.description.selector, 'Test event description');
                console.log('✅ Description field filled successfully');
            }
            
            await page.screenshot({ path: 'screenshots/tec-form-filled-debug.png', fullPage: true });
            console.log('📸 Screenshot saved: tec-form-filled-debug.png');
        }
        
    } catch (error) {
        console.error('Error:', error);
    } finally {
        await browser.close();
    }
}

inspectTECForm();