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

async function debugCurrentForm() {
    console.log('🔍 Debugging Current TEC Form State');
    console.log('==================================');
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Navigate to TEC Community Events
        console.log('🔍 Step 1: Navigating to TEC form...');
        await page.goto('https://upskill-staging.measurequick.com/events/network/add');
        await page.waitForLoadState('networkidle');
        
        console.log('📍 Current URL:', page.url());
        
        // Get page title and check for forms
        const title = await page.title();
        console.log('📋 Page Title:', title);
        
        // Check what type of page we're on
        const pageContent = await page.content();
        
        // Look for various form identifiers
        const formSelectors = [
            'form',
            '#tribe-community-events',
            '.tribe-community-events',
            '[id*="event"]',
            '[class*="event"]',
            '[id*="tribe"]',
            '[class*="tribe"]'
        ];
        
        console.log('🔍 Step 2: Analyzing page forms...');
        for (const selector of formSelectors) {
            const count = await page.locator(selector).count();
            if (count > 0) {
                console.log(`   ${selector}: ${count} found`);
                
                // Get more details about the first matching element
                try {
                    const firstElement = page.locator(selector).first();
                    const tagName = await firstElement.evaluate(el => el.tagName);
                    const id = await firstElement.getAttribute('id') || 'no-id';
                    const className = await firstElement.getAttribute('class') || 'no-class';
                    console.log(`     First match: <${tagName.toLowerCase()} id="${id}" class="${className}">`);
                } catch (e) {
                    console.log(`     Could not get details: ${e.message}`);
                }
            }
        }
        
        // Check for specific content patterns
        console.log('🔍 Step 3: Content analysis...');
        const contentChecks = {
            'TEC Community': pageContent.includes('tribe-community'),
            'Event Form': pageContent.includes('event') && pageContent.includes('form'),
            'Submit Event': pageContent.includes('submit') && pageContent.includes('event'),
            'Create Event': pageContent.includes('create') && pageContent.includes('event'),
            'Add Event': pageContent.includes('add') && pageContent.includes('event'),
            'WordPress Login': pageContent.includes('wp-login') || pageContent.includes('login'),
            'Enhanced Template': pageContent.includes('hvac-success-indicator') || pageContent.includes('hvac-tec-enhanced'),
            'Template Loading': pageContent.includes('edit-event.php') || pageContent.includes('community-edit-event')
        };
        
        for (const [check, result] of Object.entries(contentChecks)) {
            console.log(`   ${check}: ${result ? '✅' : '❌'}`);
        }
        
        // Look for specific field inputs that would indicate the form type
        console.log('🔍 Step 4: Field analysis...');
        const fieldSelectors = [
            'input[name*="title"]',
            'input[name*="EventTitle"]', 
            'textarea[name*="content"]',
            'textarea[name*="EventContent"]',
            'input[name*="date"]',
            'input[name*="EventStartDate"]',
            'select[name*="category"]',
            'input[name*="tag"]'
        ];
        
        for (const selector of fieldSelectors) {
            const count = await page.locator(selector).count();
            if (count > 0) {
                console.log(`   ${selector}: ${count} found`);
                try {
                    const name = await page.locator(selector).first().getAttribute('name');
                    const type = await page.locator(selector).first().getAttribute('type') || 'unknown';
                    console.log(`     Name: ${name}, Type: ${type}`);
                } catch (e) {
                    console.log(`     Could not get field details`);
                }
            }
        }
        
        // Check if we need authentication
        const needsAuth = pageContent.includes('login') || pageContent.includes('authenticate');
        if (needsAuth) {
            console.log('🔐 Authentication required - attempting login...');
            
            // Look for login form
            const loginForm = await page.locator('form[action*="login"], #loginform, .login-form').count();
            if (loginForm > 0) {
                try {
                    await page.fill('input[name="log"]', 'test_trainer');
                    await page.fill('input[name="pwd"]', 'TestTrainer123!');
                    await page.click('input[type="submit"]');
                    await page.waitForLoadState('networkidle');
                    
                    console.log('✅ Login successful - checking form again...');
                    
                    // Re-check after login
                    const postLoginContent = await page.content();
                    const hasFormAfterLogin = postLoginContent.includes('form');
                    const hasEventFormAfterLogin = postLoginContent.includes('event') && postLoginContent.includes('form');
                    
                    console.log('📋 Post-login analysis:');
                    console.log('   Has Form:', hasFormAfterLogin ? '✅' : '❌');
                    console.log('   Has Event Form:', hasEventFormAfterLogin ? '✅' : '❌');
                    console.log('   Enhanced Template:', postLoginContent.includes('hvac-success-indicator') ? '✅' : '❌');
                    
                } catch (e) {
                    console.log('❌ Login failed:', e.message);
                }
            }
        }
        
        // Final URL check
        console.log('📍 Final URL:', page.url());
        console.log('📊 Content Length:', pageContent.length);
        
        // Save a snippet of the content for manual inspection
        const contentSnippet = pageContent.substring(pageContent.indexOf('<body'), pageContent.indexOf('<body') + 2000);
        console.log('📄 Content snippet (first 2000 chars of body):');
        console.log('----------------------------------------');
        console.log(contentSnippet);
        console.log('----------------------------------------');
        
    } catch (error) {
        console.error('❌ Debug failed:', error.message);
    } finally {
        await browser.close();
    }
}

debugCurrentForm();