/**
 * Enhanced Field Deployment Validation Test
 * 
 * Tests that all 4 enhanced field sections are properly deployed and accessible:
 * - Excerpt field with character counter
 * - Categories multi-select with search
 * - Featured image upload with media library
 * - Tags with autocomplete functionality
 */

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

async function testEnhancedFieldDeployment() {
    console.log('🧪 Testing Enhanced Field Deployment...');
    
    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()}`);
            }
        });
        
        // Navigate to TEC add event form
        const testUrl = 'https://upskill-staging.measurequick.com/?events-community=add';
        console.log(`📍 Navigating to: ${testUrl}`);
        await page.goto(testUrl);
        
        // Wait for page load
        await page.waitForTimeout(3000);
        
        // Test Results
        const testResults = {
            enhancedTemplate: false,
            excerptField: false,
            categoriesField: false,
            featuredImageField: false,
            tagsField: false
        };
        
        // 1. Check for enhanced template indicator
        console.log('\n1️⃣ Testing Enhanced Template Indicator...');
        try {
            const enhancedIndicator = await page.waitForSelector('.hvac-success-indicator', { timeout: 5000 });
            if (enhancedIndicator) {
                const indicatorText = await enhancedIndicator.textContent();
                console.log(`✅ Enhanced template active: ${indicatorText}`);
                testResults.enhancedTemplate = true;
            }
        } catch (error) {
            console.log('❌ Enhanced template indicator not found');
        }
        
        // 2. Test Excerpt Field
        console.log('\n2️⃣ Testing Excerpt Field...');
        try {
            // Check for excerpt section
            const excerptSection = await page.waitForSelector('#hvac-excerpt-section', { timeout: 5000 });
            if (excerptSection) {
                console.log('✅ Excerpt section found');
                
                // Check for textarea
                const excerptTextarea = await page.querySelector('#hvac_post_excerpt');
                if (excerptTextarea) {
                    console.log('✅ Excerpt textarea found');
                    
                    // Test character counter
                    await excerptTextarea.fill('Test excerpt content');
                    await page.waitForTimeout(500);
                    
                    const characterCounter = await page.querySelector('#excerpt-counter .current-count');
                    if (characterCounter) {
                        const count = await characterCounter.textContent();
                        console.log(`✅ Character counter working: ${count} characters`);
                        testResults.excerptField = true;
                    }
                }
            }
        } catch (error) {
            console.log('❌ Excerpt field not accessible:', error.message);
        }
        
        // 3. Test Categories Field
        console.log('\n3️⃣ Testing Categories Field...');
        try {
            const categoriesSection = await page.waitForSelector('#hvac-categories-section', { timeout: 5000 });
            if (categoriesSection) {
                console.log('✅ Categories section found');
                
                // Check for categories search
                const searchInput = await page.querySelector('#hvac_categories_search');
                if (searchInput) {
                    console.log('✅ Categories search input found');
                    
                    // Test search functionality
                    await searchInput.fill('hvac');
                    await page.waitForTimeout(500);
                    
                    // Check for categories checkboxes
                    const categoryCheckboxes = await page.$$('.hvac-category-checkbox');
                    if (categoryCheckboxes.length > 0) {
                        console.log(`✅ Found ${categoryCheckboxes.length} category checkboxes`);
                        testResults.categoriesField = true;
                    }
                }
            }
        } catch (error) {
            console.log('❌ Categories field not accessible:', error.message);
        }
        
        // 4. Test Featured Image Field
        console.log('\n4️⃣ Testing Featured Image Field...');
        try {
            const featuredImageSection = await page.waitForSelector('#hvac-featured-image-section', { timeout: 5000 });
            if (featuredImageSection) {
                console.log('✅ Featured image section found');
                
                // Check for upload button
                const uploadButton = await page.querySelector('#hvac-upload-image-btn');
                if (uploadButton) {
                    console.log('✅ Image upload button found');
                    
                    // Check for hidden input
                    const hiddenInput = await page.querySelector('#hvac_featured_image_id');
                    if (hiddenInput) {
                        console.log('✅ Featured image hidden input found');
                        testResults.featuredImageField = true;
                    }
                }
            }
        } catch (error) {
            console.log('❌ Featured image field not accessible:', error.message);
        }
        
        // 5. Test Tags Field
        console.log('\n5️⃣ Testing Tags Field...');
        try {
            const tagsSection = await page.waitForSelector('#hvac-tags-section', { timeout: 5000 });
            if (tagsSection) {
                console.log('✅ Tags section found');
                
                // Check for tags input
                const tagsInput = await page.querySelector('#hvac_tags_input');
                if (tagsInput) {
                    console.log('✅ Tags input found');
                    
                    // Test autocomplete functionality
                    await tagsInput.fill('hv');
                    await page.waitForTimeout(500);
                    
                    // Check for suggestions dropdown
                    const suggestionsContainer = await page.querySelector('#hvac-tags-suggestions');
                    if (suggestionsContainer) {
                        console.log('✅ Tags suggestions container found');
                        testResults.tagsField = true;
                    }
                }
            }
        } catch (error) {
            console.log('❌ Tags field not accessible:', error.message);
        }
        
        // Take screenshot for visual verification
        console.log('\n📸 Taking screenshot for visual verification...');
        await page.screenshot({ 
            path: '/home/ben/dev/upskill-event-manager/test-results/enhanced-field-deployment.png',
            fullPage: true 
        });
        
        // Calculate success rate
        const successfulFields = Object.values(testResults).filter(Boolean).length;
        const totalFields = Object.keys(testResults).length;
        const successRate = Math.round((successfulFields / totalFields) * 100);
        
        // Final report
        console.log('\n📊 Enhanced Field Deployment Test Results:');
        console.log('='.repeat(50));
        console.log(`Enhanced Template: ${testResults.enhancedTemplate ? '✅' : '❌'}`);
        console.log(`Excerpt Field: ${testResults.excerptField ? '✅' : '❌'}`);
        console.log(`Categories Field: ${testResults.categoriesField ? '✅' : '❌'}`);
        console.log(`Featured Image Field: ${testResults.featuredImageField ? '✅' : '❌'}`);
        console.log(`Tags Field: ${testResults.tagsField ? '✅' : '❌'}`);
        console.log('='.repeat(50));
        console.log(`Success Rate: ${successfulFields}/${totalFields} (${successRate}%)`);
        
        if (successRate === 100) {
            console.log('\n🎉 ALL ENHANCED FIELDS SUCCESSFULLY DEPLOYED!');
            console.log('✅ 100% field control achieved');
            console.log('✅ WordPress core fields accessible');
            console.log('✅ Enhanced template fully functional');
        } else {
            console.log('\n⚠️  PARTIAL DEPLOYMENT - Some fields missing');
            console.log('❌ Enhanced field sections need additional deployment');
        }
        
        return {
            success: successRate === 100,
            successRate,
            results: testResults
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

// Run the test
if (require.main === module) {
    testEnhancedFieldDeployment()
        .then(result => {
            console.log('\n🏁 Test completed');
            process.exit(result.success ? 0 : 1);
        })
        .catch(error => {
            console.error('❌ Test runner failed:', error);
            process.exit(1);
        });
}

module.exports = { testEnhancedFieldDeployment };