/**
 * Test REST API enhancement for adding fields to TEC forms
 */

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

async function loginAsTrainer(page) {
    console.log('🔐 Logging in as test trainer...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/training-login/', {
        waitUntil: 'networkidle',
        timeout: 30000
    });
    
    await page.fill('#username, #user_login, input[name="log"]', 'test_trainer');
    await page.fill('#password, #user_pass, input[name="pwd"]', 'TestTrainer123!');
    await page.click('input[type="submit"], button[type="submit"]');
    await page.waitForTimeout(3000);
    console.log('   ✅ Logged in successfully\n');
}

(async () => {
    const browser = await chromium.launch({ 
        headless: true,  // Run headless since no X server
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const context = await browser.newContext({
        ignoreHTTPSErrors: true
    });
    
    const page = await context.newPage();
    
    // Capture console logs
    page.on('console', msg => {
        const text = msg.text();
        if (text.includes('REST') || text.includes('HVAC') || text.includes('excerpt') || text.includes('Event')) {
            console.log('   Console:', text);
        }
    });
    
    console.log('🚀 TESTING REST API ENHANCEMENT');
    console.log('=' .repeat(50));
    console.log('Time:', new Date().toLocaleString());
    console.log('=' .repeat(50) + '\n');
    
    try {
        await loginAsTrainer(page);
        
        // Test Create Event Page
        console.log('📝 TESTING CREATE EVENT PAGE');
        console.log('-'.repeat(40));
        
        await page.goto('https://upskill-staging.measurequick.com/trainer/create-event/', {
            waitUntil: 'networkidle',
            timeout: 30000
        });
        
        // Wait for any dynamic loading
        await page.waitForTimeout(3000);
        
        // Check what's actually on the page
        const pageContent = await page.evaluate(() => {
            const results = {
                formExists: !!document.querySelector('form[data-datepicker_format]'),
                formAction: document.querySelector('form')?.action,
                formMethod: document.querySelector('form')?.method,
                hiddenFields: [],
                visibleInputs: [],
                textareas: [],
                selects: [],
                buttons: [],
                tribeElements: document.querySelectorAll('[class*="tribe"]').length,
                restApiScriptLoaded: typeof window.HVACRestEventSubmission !== 'undefined',
                jqueryLoaded: typeof jQuery !== 'undefined',
                formHTML: document.querySelector('form')?.outerHTML?.substring(0, 500)
            };
            
            // Check hidden fields
            document.querySelectorAll('input[type="hidden"]').forEach(input => {
                results.hiddenFields.push({
                    name: input.name,
                    id: input.id,
                    value: input.value?.substring(0, 50)
                });
            });
            
            // Check visible inputs
            document.querySelectorAll('input:not([type="hidden"])').forEach(input => {
                results.visibleInputs.push({
                    type: input.type,
                    name: input.name,
                    id: input.id,
                    placeholder: input.placeholder
                });
            });
            
            // Check textareas
            document.querySelectorAll('textarea').forEach(textarea => {
                results.textareas.push({
                    name: textarea.name,
                    id: textarea.id,
                    placeholder: textarea.placeholder
                });
            });
            
            // Check selects
            document.querySelectorAll('select').forEach(select => {
                results.selects.push({
                    name: select.name,
                    id: select.id,
                    optionCount: select.options.length
                });
            });
            
            // Check buttons
            document.querySelectorAll('button, input[type="submit"]').forEach(button => {
                results.buttons.push({
                    type: button.type || button.tagName,
                    text: button.textContent || button.value
                });
            });
            
            return results;
        });
        
        console.log('\n📊 FORM ANALYSIS:');
        console.log('   Form exists:', pageContent.formExists ? '✅' : '❌');
        console.log('   jQuery loaded:', pageContent.jqueryLoaded ? '✅' : '❌');
        console.log('   REST API script:', pageContent.restApiScriptLoaded ? '✅' : '❌');
        console.log('   Tribe elements found:', pageContent.tribeElements);
        
        console.log('\n   Hidden fields:', pageContent.hiddenFields.length);
        pageContent.hiddenFields.forEach(field => {
            console.log(`     - ${field.name || field.id}: ${field.value || '(empty)'}`);
        });
        
        console.log('\n   Visible inputs:', pageContent.visibleInputs.length);
        if (pageContent.visibleInputs.length > 0) {
            pageContent.visibleInputs.forEach(input => {
                console.log(`     - ${input.type}: ${input.name || input.id}`);
            });
        } else {
            console.log('     ❌ No visible input fields!');
        }
        
        console.log('\n   Textareas:', pageContent.textareas.length);
        if (pageContent.textareas.length > 0) {
            pageContent.textareas.forEach(textarea => {
                console.log(`     - ${textarea.name || textarea.id}: "${textarea.placeholder}"`);
            });
        } else {
            console.log('     ❌ No textarea fields!');
        }
        
        console.log('\n   Selects:', pageContent.selects.length);
        if (pageContent.selects.length > 0) {
            pageContent.selects.forEach(select => {
                console.log(`     - ${select.name || select.id}: ${select.optionCount} options`);
            });
        } else {
            console.log('     ❌ No select fields!');
        }
        
        console.log('\n   Buttons:', pageContent.buttons.length);
        if (pageContent.buttons.length > 0) {
            pageContent.buttons.forEach(button => {
                console.log(`     - ${button.type}: "${button.text}"`);
            });
        } else {
            console.log('     ❌ No submit buttons!');
        }
        
        // Now try to manually inject the REST API script if it's not loaded
        if (!pageContent.restApiScriptLoaded) {
            console.log('\n🔧 INJECTING REST API SCRIPT...');
            
            await page.evaluate(() => {
                const script = document.createElement('script');
                script.src = '/wp-content/plugins/hvac-community-events/assets/js/hvac-rest-api-event-submission.js';
                script.onload = () => console.log('REST API script injected successfully');
                script.onerror = () => console.error('Failed to inject REST API script');
                document.head.appendChild(script);
            });
            
            await page.waitForTimeout(2000);
            
            // Check if it loaded now
            const scriptLoaded = await page.evaluate(() => {
                return typeof window.HVACRestEventSubmission !== 'undefined';
            });
            
            console.log('   Script loaded after injection:', scriptLoaded ? '✅' : '❌');
            
            if (scriptLoaded) {
                // Try to initialize it
                await page.evaluate(() => {
                    if (typeof HVACRestEventSubmission !== 'undefined' && typeof HVACRestEventSubmission.init === 'function') {
                        HVACRestEventSubmission.init();
                        console.log('REST API initialized manually');
                    }
                });
                
                await page.waitForTimeout(2000);
                
                // Check if excerpt field was added
                const excerptAdded = await page.evaluate(() => {
                    return !!document.querySelector('#event_excerpt');
                });
                
                console.log('   Excerpt field added:', excerptAdded ? '✅' : '❌');
            }
        }
        
        // Take screenshot
        await page.screenshot({ path: 'create-event-form-debug.png', fullPage: true });
        console.log('\n📸 Screenshot saved: create-event-form-debug.png');
        
        // Test the TEC shortcode directly
        console.log('\n🔍 TESTING TEC SHORTCODE DIRECTLY...');
        
        // Create a test page with just the TEC shortcode
        const testHTML = `
            <div id="test-container">
                <h2>Direct TEC Shortcode Test</h2>
                <div id="shortcode-result"></div>
            </div>
        `;
        
        await page.evaluate((html) => {
            const container = document.createElement('div');
            container.innerHTML = html;
            document.body.appendChild(container);
            
            // Try to call do_shortcode via AJAX
            if (typeof jQuery !== 'undefined' && typeof hvac_ajax !== 'undefined') {
                jQuery.post(hvac_ajax.ajax_url, {
                    action: 'hvac_test_shortcode',
                    shortcode: '[tribe_community_events]',
                    nonce: hvac_ajax.nonce
                }, function(response) {
                    if (response.success) {
                        jQuery('#shortcode-result').html(response.data);
                        console.log('Shortcode rendered via AJAX');
                    } else {
                        console.error('Shortcode AJAX failed:', response);
                    }
                });
            }
        }, testHTML);
        
        await page.waitForTimeout(3000);
        
        // Final check
        const finalCheck = await page.evaluate(() => {
            return {
                excerptFieldExists: !!document.querySelector('#event_excerpt'),
                titleFieldExists: !!document.querySelector('input[name="post_title"], #EventTitle'),
                descriptionFieldExists: !!document.querySelector('textarea[name="post_content"], #EventDescription'),
                dateFieldExists: !!document.querySelector('input[name="EventStartDate"], #EventStartDate'),
                submitButtonExists: !!document.querySelector('input[type="submit"], button[type="submit"]')
            };
        });
        
        console.log('\n✅ FINAL FIELD CHECK:');
        console.log('   Title field:', finalCheck.titleFieldExists ? '✅' : '❌');
        console.log('   Description field:', finalCheck.descriptionFieldExists ? '✅' : '❌');
        console.log('   Date field:', finalCheck.dateFieldExists ? '✅' : '❌');
        console.log('   Submit button:', finalCheck.submitButtonExists ? '✅' : '❌');
        console.log('   Excerpt field:', finalCheck.excerptFieldExists ? '✅' : '❌');
        
        console.log('\n💡 DIAGNOSIS:');
        if (!finalCheck.titleFieldExists && !finalCheck.descriptionFieldExists) {
            console.log('   ⚠️  TEC form is rendering but fields are not visible');
            console.log('   This is a TEC plugin configuration issue, not a shortcode conflict');
            console.log('   Possible causes:');
            console.log('   - TEC Community Events settings need configuration');
            console.log('   - User permissions issue');
            console.log('   - TEC template override issue');
            console.log('   - Missing TEC form template files');
        }
        
    } catch (error) {
        console.error('❌ Error during testing:', error.message);
    } finally {
        await browser.close();
        console.log('\n✅ Test complete');
    }
})();