/**
 * Debug Description Field Population Issue
 * Investigate why tcepostcontent field isn't being populated by our system
 */

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

const config = {
    baseUrl: process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com',
    testEventId: '10000028',
    credentials: {
        username: 'test_trainer',
        password: 'TestTrainer123!'
    }
};

console.log('🐛 Debug Description Field Population Issue');
console.log(`🎯 Target Event ID: ${config.testEventId}`);
console.log('🔍 Investigating #tcepostcontent field population');
console.log('');

async function debugDescriptionField() {
    const browser = await chromium.launch({ headless: true }); // Run in headless mode
    const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 }
    });
    const page = await context.newPage();

    // Enable detailed console logging
    page.on('console', msg => {
        if (msg.text().includes('HVAC') || msg.text().includes('Description')) {
            console.log(`🔍 [Console] ${msg.text()}`);
        }
    });

    try {
        // Login
        console.log('🔐 Logging in...');
        await page.goto(`${config.baseUrl}/training-login/`);
        await page.fill('input[name="log"]', config.credentials.username);
        await page.fill('input[name="pwd"]', config.credentials.password);
        await page.click('button[type="submit"]');
        await page.waitForLoadState('networkidle');

        // Navigate to event edit page
        console.log('📋 Navigating to event edit page...');
        await page.goto(`${config.baseUrl}/trainer/event/manage/?event_id=${config.testEventId}`);
        await page.waitForSelector('#tribe-community-events');
        await page.waitForTimeout(3000); // Let our system run

        console.log('🐛 DEBUGGING DESCRIPTION FIELD');
        console.log('===============================');

        // Step 1: Check if our comprehensive system loaded
        const systemStatus = await page.evaluate(() => {
            return {
                systemLoaded: typeof hvac_event_comprehensive !== 'undefined',
                eventDataExists: typeof hvac_event_comprehensive !== 'undefined' && 
                               hvac_event_comprehensive.event_data !== null,
                debugMode: typeof hvac_event_comprehensive !== 'undefined' && 
                          hvac_event_comprehensive.debug,
                contentData: typeof hvac_event_comprehensive !== 'undefined' && 
                           hvac_event_comprehensive.event_data ? 
                           hvac_event_comprehensive.event_data.core?.content : null
            };
        });

        console.log('\n🔧 SYSTEM STATUS:');
        console.log(`System Loaded: ${systemStatus.systemLoaded ? '✅' : '❌'}`);
        console.log(`Event Data Exists: ${systemStatus.eventDataExists ? '✅' : '❌'}`);
        console.log(`Debug Mode: ${systemStatus.debugMode ? '✅' : '❌'}`);
        console.log(`Content Data Available: ${systemStatus.contentData ? '✅' : '❌'}`);
        if (systemStatus.contentData) {
            console.log(`Content: "${systemStatus.contentData.substring(0, 100)}..."`);
        }

        // Step 2: Check the tcepostcontent field status
        const fieldStatus = await page.evaluate(() => {
            const textarea = document.querySelector('#tcepostcontent');
            if (!textarea) return { error: 'Field not found' };

            return {
                exists: true,
                visible: textarea.offsetHeight > 0 && textarea.offsetWidth > 0,
                value: textarea.value,
                placeholder: textarea.placeholder,
                readOnly: textarea.readOnly,
                disabled: textarea.disabled,
                style: {
                    display: getComputedStyle(textarea).display,
                    visibility: getComputedStyle(textarea).visibility,
                    opacity: getComputedStyle(textarea).opacity
                }
            };
        });

        console.log('\n📝 TCEPOSTCONTENT FIELD STATUS:');
        console.log('===============================');
        if (fieldStatus.error) {
            console.log(`❌ ${fieldStatus.error}`);
        } else {
            console.log(`Field Exists: ✅`);
            console.log(`Visible: ${fieldStatus.visible ? '✅' : '❌'}`);
            console.log(`Current Value: "${fieldStatus.value}"`);
            console.log(`Placeholder: "${fieldStatus.placeholder}"`);
            console.log(`Read Only: ${fieldStatus.readOnly ? '❌' : '✅'}`);
            console.log(`Disabled: ${fieldStatus.disabled ? '❌' : '✅'}`);
            console.log(`Display: ${fieldStatus.style.display}`);
            console.log(`Visibility: ${fieldStatus.style.visibility}`);
            console.log(`Opacity: ${fieldStatus.style.opacity}`);
        }

        // Step 3: Manually test field population
        console.log('\n🧪 MANUAL FIELD POPULATION TEST:');
        console.log('=================================');
        
        const testContent = "This is a test description to verify field population works!";
        
        const populationResult = await page.evaluate((content) => {
            const textarea = document.querySelector('#tcepostcontent');
            if (!textarea) return { error: 'Field not found for population test' };

            try {
                // Try multiple population methods
                const results = {};

                // Method 1: Direct value assignment
                textarea.value = content;
                results.directValue = textarea.value === content;

                // Method 2: Using jQuery if available
                if (typeof $ !== 'undefined') {
                    $(textarea).val(content + ' (jQuery)');
                    results.jquery = $(textarea).val().includes('jQuery');
                } else {
                    results.jquery = 'jQuery not available';
                }

                // Method 3: Trigger events
                textarea.dispatchEvent(new Event('input', { bubbles: true }));
                textarea.dispatchEvent(new Event('change', { bubbles: true }));
                results.eventsTriggered = true;

                // Method 4: Focus and blur
                textarea.focus();
                textarea.blur();
                results.focusBlur = true;

                return { success: true, results, finalValue: textarea.value };
            } catch (error) {
                return { error: error.message };
            }
        }, testContent);

        if (populationResult.error) {
            console.log(`❌ Population test failed: ${populationResult.error}`);
        } else {
            console.log(`✅ Population test completed`);
            console.log(`Direct Value: ${populationResult.results.directValue ? '✅' : '❌'}`);
            console.log(`jQuery: ${populationResult.results.jquery === true ? '✅' : populationResult.results.jquery === false ? '❌' : '⚠️ ' + populationResult.results.jquery}`);
            console.log(`Events Triggered: ${populationResult.results.eventsTriggered ? '✅' : '❌'}`);
            console.log(`Focus/Blur: ${populationResult.results.focusBlur ? '✅' : '❌'}`);
            console.log(`Final Value: "${populationResult.finalValue}"`);
        }

        // Step 4: Check if TinyMCE is interfering
        const tinymceStatus = await page.evaluate(() => {
            return {
                available: typeof tinymce !== 'undefined',
                editors: typeof tinymce !== 'undefined' ? Object.keys(tinymce.editors) : [],
                tcepostcontentEditor: typeof tinymce !== 'undefined' ? 
                    (tinymce.get('tcepostcontent') ? true : false) : false
            };
        });

        console.log('\n📝 TINYMCE STATUS:');
        console.log('==================');
        console.log(`TinyMCE Available: ${tinymceStatus.available ? '✅' : '❌'}`);
        console.log(`Total Editors: ${tinymceStatus.editors.length}`);
        if (tinymceStatus.editors.length > 0) {
            console.log(`Editor IDs: ${tinymceStatus.editors.join(', ')}`);
        }
        console.log(`tcepostcontent Editor: ${tinymceStatus.tcepostcontentEditor ? '✅ (INTERFERENCE POSSIBLE)' : '❌'}`);

        // Step 5: Try to populate with our actual comprehensive system approach
        console.log('\n🔄 TESTING COMPREHENSIVE SYSTEM APPROACH:');
        console.log('=========================================');
        
        const comprehensiveTest = await page.evaluate(() => {
            if (typeof hvac_event_comprehensive === 'undefined' || !hvac_event_comprehensive.event_data) {
                return { error: 'Comprehensive system not loaded' };
            }

            const content = hvac_event_comprehensive.event_data.core?.content;
            if (!content) {
                return { error: 'No content data available' };
            }

            // Test our comprehensive system's field population function
            const selectors = [
                '#tcepostcontent',
                'textarea[name="tcepostcontent"]',
                '#post_content',
                'textarea[name="post_content"]',
                '.tribe-community-events-form-content textarea',
                '.wp-editor-area'
            ];

            let field = null;
            let usedSelector = null;

            // Find the field using our selectors
            for (let selector of selectors) {
                try {
                    const element = document.querySelector(selector);
                    if (element) {
                        field = element;
                        usedSelector = selector;
                        break;
                    }
                } catch (e) {
                    // Continue to next selector
                }
            }

            if (!field) {
                return { error: 'No field found with comprehensive system selectors' };
            }

            // Try to populate using comprehensive system logic
            try {
                // Handle TinyMCE if present
                if (typeof tinymce !== 'undefined') {
                    const editor = tinymce.get(field.id);
                    if (editor) {
                        editor.setContent(content);
                        return { 
                            success: true, 
                            method: 'TinyMCE', 
                            selector: usedSelector,
                            finalValue: editor.getContent()
                        };
                    }
                }
                
                // Handle regular form fields
                field.value = content;
                field.dispatchEvent(new Event('change', { bubbles: true }));
                field.dispatchEvent(new Event('input', { bubbles: true }));
                
                return { 
                    success: true, 
                    method: 'Direct', 
                    selector: usedSelector,
                    finalValue: field.value
                };
                
            } catch (error) {
                return { error: `Population failed: ${error.message}` };
            }
        });

        if (comprehensiveTest.error) {
            console.log(`❌ ${comprehensiveTest.error}`);
        } else {
            console.log(`✅ Comprehensive system approach worked!`);
            console.log(`Method: ${comprehensiveTest.method}`);
            console.log(`Selector: ${comprehensiveTest.selector}`);
            console.log(`Final Value: "${comprehensiveTest.finalValue.substring(0, 100)}..."`);
        }

        // Wait a bit to see the result
        await page.waitForTimeout(2000);

        // Take screenshot for visual verification
        await page.screenshot({ 
            path: 'test-results/description-field-debug.png',
            fullPage: true 
        });

        console.log('\n📸 Screenshot saved: test-results/description-field-debug.png');
        console.log('\n✅ Description field debug completed!');

        return {
            systemStatus,
            fieldStatus,
            populationResult,
            tinymceStatus,
            comprehensiveTest
        };

    } catch (error) {
        console.error('❌ Debug failed:', error);
        await page.screenshot({ path: 'test-results/description-debug-error.png' });
        throw error;
    } finally {
        await browser.close();
    }
}

// Run the debug
debugDescriptionField()
    .then(() => {
        console.log('\n🎯 Description field debug completed successfully');
        process.exit(0);
    })
    .catch((error) => {
        console.error('\n💥 Description field debug failed:', error);
        process.exit(1);
    });