/**
 * Enhanced Field Deployment Validation Test with Authentication
 * 
 * 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
 * 
 * This version logs in as a trainer first to access the TEC form
 */

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

async function testEnhancedFieldDeploymentWithAuth() {
    console.log('🧪 Testing Enhanced Field Deployment (with Authentication)...');
    
    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()}`);
            }
        });
        
        // Step 1: Login as trainer first
        console.log('🔐 Step 1: Logging in as trainer...');
        await page.goto('https://upskill-staging.measurequick.com/training-login/');
        await page.waitForTimeout(2000);
        
        // Fill login form
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'TestTrainer123!');
        await page.click('#wp-submit');
        
        // Wait for login redirect
        await page.waitForTimeout(3000);
        
        // Verify login success
        const currentUrl = page.url();
        if (currentUrl.includes('dashboard')) {
            console.log('✅ Login successful - redirected to dashboard');
        } else {
            console.log('⚠️ Login redirect unclear, continuing...');
        }
        
        // Step 2: Navigate to TEC form - try authenticated URLs
        console.log('\n🌐 Step 2: Accessing TEC event form...');
        
        const authTestUrls = [
            'https://upskill-staging.measurequick.com/?events-community=add',
            'https://upskill-staging.measurequick.com/events/community/add/',
            'https://upskill-staging.measurequick.com/trainer/add-event/',
            'https://upskill-staging.measurequick.com/event-add/',
            'https://upskill-staging.measurequick.com/submit-event/'
        ];
        
        let formFound = false;
        let workingUrl = '';
        
        for (const url of authTestUrls) {
            console.log(`🌐 Testing authenticated URL: ${url}`);
            
            try {
                await page.goto(url);
                await page.waitForTimeout(2000);
                
                // Check for TEC form elements
                const tecSelectors = [
                    '#tribe-community-events-form',
                    '.tribe-community-events',
                    '#tribe-events-community-edit-form',
                    'form[data-datepicker_format]',
                    '[name="post_title"]',
                    '[name="post_content"]'
                ];
                
                for (const selector of tecSelectors) {
                    try {
                        const element = await page.waitForSelector(selector, { timeout: 2000 });
                        if (element) {
                            console.log(`✅ Found TEC form element: ${selector}`);
                            formFound = true;
                            workingUrl = url;
                            break;
                        }
                    } catch (e) {
                        // Continue to next selector
                    }
                }
                
                if (formFound) break;
                
            } catch (error) {
                console.log(`❌ URL failed: ${error.message}`);
            }
        }
        
        if (!formFound) {
            console.log('❌ TEC form not found even with authentication');
            
            // Try to find form through navigation
            console.log('🔍 Checking dashboard for event creation links...');
            await page.goto('https://upskill-staging.measurequick.com/trainer/dashboard/');
            await page.waitForTimeout(2000);
            
            // Look for add event links
            const links = await page.$$eval('a', links => 
                links.filter(link => 
                    link.textContent.toLowerCase().includes('add') ||
                    link.textContent.toLowerCase().includes('create') ||
                    link.textContent.toLowerCase().includes('submit') ||
                    link.href.includes('event')
                ).map(link => ({ text: link.textContent.trim(), href: link.href }))
            );
            
            console.log('🔗 Found potential event links:');
            links.forEach(link => {
                console.log(`   - "${link.text}": ${link.href}`);
            });
            
            // Try the first promising link
            if (links.length > 0) {
                const firstLink = links[0];
                console.log(`🎯 Trying first link: ${firstLink.href}`);
                await page.goto(firstLink.href);
                await page.waitForTimeout(2000);
                
                // Check again for form
                for (const selector of ['#tribe-community-events-form', '.tribe-community-events', 'form[data-datepicker_format]']) {
                    try {
                        const element = await page.waitForSelector(selector, { timeout: 2000 });
                        if (element) {
                            console.log(`✅ Found TEC form via dashboard link: ${selector}`);
                            formFound = true;
                            workingUrl = firstLink.href;
                            break;
                        }
                    } catch (e) {
                        // Continue
                    }
                }
            }
        }
        
        if (!formFound) {
            await page.screenshot({ 
                path: '/home/ben/dev/upskill-event-manager/test-results/tec-form-not-found.png',
                fullPage: true 
            });
            
            return {
                success: false,
                error: 'TEC Community Events form not accessible even with authentication'
            };
        }
        
        console.log(`🎯 TEC Form found at: ${workingUrl}`);
        
        // Step 3: Test Enhanced Template and Fields
        console.log('\n🧪 Step 3: Testing Enhanced Template and Fields...');
        
        // 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');
            
            // Check if we're seeing the standard TEC form
            try {
                const standardForm = await page.waitForSelector('#tribe-community-events-form', { timeout: 2000 });
                if (standardForm) {
                    console.log('📋 Standard TEC form detected - enhanced template not overriding');
                }
            } catch (e) {
                console.log('⚠️ No recognizable TEC form structure 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: 3000 });
            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 for enhanced field validation');
                    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');
        }
        
        // 3. Test Categories Field
        console.log('\n3️⃣ Testing Categories Field...');
        try {
            const categoriesSection = await page.waitForSelector('#hvac-categories-section', { timeout: 3000 });
            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');
        }
        
        // 4. Test Featured Image Field
        console.log('\n4️⃣ Testing Featured Image Field...');
        try {
            const featuredImageSection = await page.waitForSelector('#hvac-featured-image-section', { timeout: 3000 });
            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');
        }
        
        // 5. Test Tags Field
        console.log('\n5️⃣ Testing Tags Field...');
        try {
            const tagsSection = await page.waitForSelector('#hvac-tags-section', { timeout: 3000 });
            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');
        }
        
        // 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-auth.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 (Authenticated):');
        console.log('='.repeat(60));
        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(60));
        console.log(`Success Rate: ${successfulFields}/${totalFields} (${successRate}%)`);
        console.log(`Working TEC URL: ${workingUrl}`);
        
        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 if (successRate > 0) {
            console.log('\n⚠️  PARTIAL DEPLOYMENT SUCCESS');
            console.log(`✅ ${successfulFields} enhanced fields working`);
            console.log(`❌ ${totalFields - successfulFields} fields need debugging`);
        } else {
            console.log('\n❌ ENHANCED TEMPLATE NOT ACTIVE');
            console.log('🔧 Template override not working - using standard TEC form');
            console.log('💡 Possible issues:');
            console.log('   - Theme template not properly deployed');
            console.log('   - Template hierarchy not working');
            console.log('   - TEC caching preventing override');
        }
        
        return {
            success: successRate === 100,
            successRate,
            results: testResults,
            workingUrl: workingUrl
        };
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return { success: false, error: error.message };
    } finally {
        await browser.close();
    }
}

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

module.exports = { testEnhancedFieldDeploymentWithAuth };