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

(async () => {
    console.log('🔍 Detailed TEC Form Analysis');
    
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();

    try {
        const baseUrl = 'https://upskill-staging.measurequick.com';
        const username = 'test_trainer';
        const password = 'TestTrainer123!';

        console.log('📝 Logging in...');
        await page.goto(`${baseUrl}/trainer/login/`);
        await page.waitForSelector('#user_login', { timeout: 10000 });
        
        await page.fill('#user_login', username);
        await page.fill('#user_pass', password);
        await page.click('#wp-submit');
        
        await page.waitForURL('**/trainer/dashboard/**', { timeout: 15000 });
        console.log('✅ Login successful\n');

        // Test Create Event Page
        console.log('🧪 Analyzing Create Event Page Form Elements');
        await page.goto(`${baseUrl}/trainer/create-event/`);
        await page.waitForTimeout(3000);

        // Check for specific form fields that TEC should have
        const formElements = {
            'Event Title': await page.$$('input[name="post_title"], input[placeholder*="title"], input[placeholder*="Title"]'),
            'Event Description': await page.$$('textarea[name="post_content"], textarea[name="tcepostcontent"], .wp-editor-area'),
            'Event Date': await page.$$('input[name*="event"], input[type="date"], input[name*="Date"]'),
            'Submit Button': await page.$$('input[type="submit"], button[type="submit"], .tribe-events-button'),
            'Tribe Elements': await page.$$('[class*="tribe"], [id*="tribe"]'),
            'Community Form': await page.$$('.tribe-community-events-form, .tribe-events-community-form'),
            'TEC Scripts': await page.$$('script[src*="tribe"], script[src*="community"]')
        };

        console.log('📊 Form Elements Found:');
        for (const [name, elements] of Object.entries(formElements)) {
            console.log(`   ${name}: ${elements.length} element(s)`);
            
            if (elements.length > 0 && name === 'Event Title') {
                // Get details about the title field
                const titleField = elements[0];
                const id = await titleField.getAttribute('id');
                const name_attr = await titleField.getAttribute('name');
                const placeholder = await titleField.getAttribute('placeholder');
                console.log(`     - ID: ${id}, Name: ${name_attr}, Placeholder: ${placeholder}`);
            }
        }

        // Check for actual TEC shortcode output
        const pageHTML = await page.content();
        const shortcodeIndicators = {
            'tribe_community_events shortcode': pageHTML.includes('[tribe_community_events'),
            'TEC form wrapper': pageHTML.includes('tribe-events') || pageHTML.includes('tribe-community'),
            'Community events CSS': pageHTML.includes('tribe-events-community') || pageHTML.includes('community-events'),
            'Event form classes': pageHTML.includes('event-form') || pageHTML.includes('events-form'),
            'HVAC shortcode debug': pageHTML.includes('HVAC_Shortcodes') || pageHTML.includes('hvac_create_event')
        };

        console.log('\n🔍 Shortcode Output Analysis:');
        for (const [indicator, found] of Object.entries(shortcodeIndicators)) {
            console.log(`   ${indicator}: ${found ? '✅' : '❌'}`);
        }

        // Check if we can actually interact with the form
        console.log('\n🧪 Form Interaction Test:');
        
        try {
            // Try to find and fill the event title field
            const titleSelectors = [
                'input[name="post_title"]',
                'input[placeholder*="title"]',
                'input[placeholder*="Title"]',
                '#post_title',
                '.tribe-events-community-post-title',
                'input[type="text"]:first-of-type'
            ];

            let titleField = null;
            for (const selector of titleSelectors) {
                try {
                    titleField = await page.$(selector);
                    if (titleField) {
                        console.log(`   ✅ Found title field with selector: ${selector}`);
                        break;
                    }
                } catch (e) {
                    // Continue trying
                }
            }

            if (titleField) {
                await titleField.fill('Test Event Title');
                const value = await titleField.inputValue();
                console.log(`   ✅ Successfully filled title field with: "${value}"`);
            } else {
                console.log('   ❌ Could not find event title field');
            }

            // Look for submit button
            const submitSelectors = [
                'input[type="submit"]',
                'button[type="submit"]',
                '.tribe-events-button',
                'input[value*="Submit"]',
                'button:contains("Submit")'
            ];

            let submitButton = null;
            for (const selector of submitSelectors) {
                try {
                    submitButton = await page.$(selector);
                    if (submitButton) {
                        const text = await submitButton.textContent() || await submitButton.getAttribute('value');
                        console.log(`   ✅ Found submit button: "${text}" (${selector})`);
                        break;
                    }
                } catch (e) {
                    // Continue trying
                }
            }

            if (!submitButton) {
                console.log('   ❌ Could not find submit button');
            }

        } catch (error) {
            console.log(`   ❌ Form interaction error: ${error.message}`);
        }

        // Get page source snippet around form
        const bodyHTML = await page.$eval('body', el => el.innerHTML);
        const formStart = bodyHTML.indexOf('<form');
        if (formStart !== -1) {
            const formEnd = bodyHTML.indexOf('</form>', formStart) + 7;
            const formHTML = bodyHTML.substring(formStart, Math.min(formEnd, formStart + 1000));
            console.log('\n📝 Form HTML Sample:');
            console.log(formHTML.substring(0, 500) + '...');
        }

        await page.screenshot({ path: 'tec-form-detailed-analysis.png', fullPage: true });
        console.log('\n📸 Screenshot saved: tec-form-detailed-analysis.png');

    } catch (error) {
        console.error('❌ Test failed:', error.message);
    } finally {
        await browser.close();
    }
})();