/**
 * Debug HVAC Event Management Page
 * 
 * Analyzes the actual event creation/management interface to understand
 * what system is being used and how to integrate enhanced fields
 */

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

async function debugHvacEventManage() {
    console.log('🔍 Debugging HVAC Event Management System...');
    
    const browser = await chromium.launch({ 
        headless: true,
        slowMo: 500
    });
    
    try {
        const context = await browser.newContext({
            viewport: { width: 1200, height: 800 }
        });
        
        const page = await context.newPage();
        
        // Enable console logging
        page.on('console', msg => {
            if (msg.type() === 'log' || msg.type() === 'error') {
                console.log(`🖥️  ${msg.text()}`);
            }
        });
        
        // Login as trainer
        console.log('🔐 Logging in as trainer...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForTimeout(2000);
        
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        await page.waitForTimeout(3000);
        
        // Navigate to event management page
        console.log('🎯 Accessing event management page...');
        await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
        await page.waitForTimeout(3000);
        
        // Analyze page structure
        console.log('\n📋 Analyzing page structure...');
        
        // Check page title
        const title = await page.title();
        console.log(`📄 Page Title: ${title}`);
        
        // Check for different form systems
        const formSystems = {
            tecCommunity: {
                selectors: ['#tribe-community-events-form', '.tribe-community-events', '[name="community-event"]'],
                name: 'TEC Community Events'
            },
            tecStandard: {
                selectors: ['#tribe-events-form', '.tribe-events', '[name="tribe_events"]'],
                name: 'TEC Standard Forms'
            },
            hvacCustom: {
                selectors: ['.hvac-event-form', '#hvac-event-manage', '.hvac-form-wrapper'],
                name: 'HVAC Custom Event System'
            },
            wordpress: {
                selectors: ['#post', '.wp-admin', '#poststuff'],
                name: 'WordPress Admin Interface'
            }
        };
        
        let detectedSystem = 'unknown';
        
        for (const [systemKey, system] of Object.entries(formSystems)) {
            for (const selector of system.selectors) {
                try {
                    const element = await page.waitForSelector(selector, { timeout: 2000 });
                    if (element) {
                        console.log(`✅ Detected: ${system.name} (${selector})`);
                        detectedSystem = systemKey;
                        break;
                    }
                } catch (e) {
                    // Continue checking
                }
            }
            if (detectedSystem !== 'unknown') break;
        }
        
        if (detectedSystem === 'unknown') {
            console.log('⚠️ No recognized event management system detected');
        }
        
        // Check for form fields
        console.log('\n📝 Analyzing available form fields...');
        
        const fieldTypes = {
            title: ['[name="post_title"]', '#title', '[name="event_title"]', '.event-title input'],
            description: ['[name="post_content"]', '#content', '[name="event_description"]', '.event-description textarea'],
            excerpt: ['[name="post_excerpt"]', '#excerpt', '[name="event_excerpt"]', '.event-excerpt textarea'],
            categories: ['[name="tax_input[tribe_events_cat][]"]', '[name="tribe_events_cat"]', '.event-categories input'],
            tags: ['[name="tax_input[post_tag][]"]', '[name="tags"]', '.event-tags input'],
            featuredImage: ['#set-post-thumbnail', '[name="_thumbnail_id"]', '.featured-image input'],
            startDate: ['[name="EventStartDate"]', '[name="event_start"]', '.event-start input'],
            endDate: ['[name="EventEndDate"]', '[name="event_end"]', '.event-end input']
        };
        
        const foundFields = {};
        
        for (const [fieldName, selectors] of Object.entries(fieldTypes)) {
            foundFields[fieldName] = false;
            
            for (const selector of selectors) {
                try {
                    const element = await page.waitForSelector(selector, { timeout: 1000 });
                    if (element) {
                        console.log(`✅ Found ${fieldName} field: ${selector}`);
                        foundFields[fieldName] = true;
                        break;
                    }
                } catch (e) {
                    // Continue
                }
            }
            
            if (!foundFields[fieldName]) {
                console.log(`❌ Missing ${fieldName} field`);
            }
        }
        
        // Check for enhanced template elements
        console.log('\n🔧 Checking for enhanced template elements...');
        
        const enhancedElements = [
            '.hvac-success-indicator',
            '#hvac-excerpt-section',
            '#hvac-categories-section',
            '#hvac-featured-image-section',
            '#hvac-tags-section'
        ];
        
        let enhancedFound = 0;
        
        for (const selector of enhancedElements) {
            try {
                const element = await page.waitForSelector(selector, { timeout: 1000 });
                if (element) {
                    console.log(`✅ Enhanced element found: ${selector}`);
                    enhancedFound++;
                }
            } catch (e) {
                console.log(`❌ Enhanced element missing: ${selector}`);
            }
        }
        
        // Get page HTML structure for analysis
        console.log('\n🔍 Analyzing HTML structure...');
        
        const bodyClasses = await page.evaluate(() => {
            return document.body.className;
        });
        console.log(`📋 Body classes: ${bodyClasses}`);
        
        const formElements = await page.$$eval('form', forms => {
            return forms.map((form, index) => ({
                index: index,
                id: form.id || 'no-id',
                classes: form.className || 'no-classes',
                action: form.action || 'no-action',
                method: form.method || 'GET'
            }));
        });
        
        console.log('📋 Forms found:');
        formElements.forEach(form => {
            console.log(`   Form ${form.index}: id="${form.id}", classes="${form.classes}", action="${form.action}"`);
        });
        
        // Take detailed screenshot
        console.log('\n📸 Taking detailed screenshot...');
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/hvac-event-manage-analysis.png',
            fullPage: true 
        });
        
        // Check current URL and any redirects
        const currentUrl = page.url();
        console.log(`🔗 Current URL: ${currentUrl}`);
        
        // Summary
        console.log('\n📊 HVAC Event Management Analysis Summary:');
        console.log('='.repeat(60));
        console.log(`Detected System: ${formSystems[detectedSystem]?.name || 'Unknown'}`);
        console.log(`Enhanced Elements: ${enhancedFound}/${enhancedElements.length}`);
        console.log(`Form Fields Found: ${Object.values(foundFields).filter(Boolean).length}/${Object.keys(foundFields).length}`);
        console.log(`Current URL: ${currentUrl}`);
        
        if (detectedSystem === 'hvacCustom') {
            console.log('\n💡 Recommendations:');
            console.log('   - System uses custom HVAC event management');
            console.log('   - Enhanced TEC template may not apply here');
            console.log('   - Need to modify HVAC custom forms for enhanced fields');
        } else if (detectedSystem === 'tecCommunity' || detectedSystem === 'tecStandard') {
            console.log('\n💡 Recommendations:');
            console.log('   - TEC system detected');
            console.log('   - Enhanced template should work');
            console.log('   - Check template override configuration');
        } else {
            console.log('\n💡 Recommendations:');
            console.log('   - Unknown system - needs further investigation');
            console.log('   - Check if TEC Community Events is properly configured');
            console.log('   - Verify user permissions for community submissions');
        }
        
        return {
            success: true,
            detectedSystem: detectedSystem,
            enhancedElements: enhancedFound,
            foundFields: foundFields,
            currentUrl: currentUrl
        };
        
    } catch (error) {
        console.error('❌ Debug failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the debug
if (require.main === module) {
    debugHvacEventManage()
        .then(result => {
            console.log('\n🏁 HVAC Event Management Debug Complete');
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Debug runner failed:', error);
            process.exit(1);
        });
}

module.exports = { debugHvacEventManage };