/**
 * Test Event Manager Consolidation
 * 
 * Tests the consolidated HVAC Event Manager to ensure all functionality
 * from the 8+ previous implementations works correctly
 */

const { test, expect } = require('@playwright/test');

test.describe('HVAC Event Manager Consolidation Tests', () => {
    
    test.beforeEach(async ({ page }) => {
        // Set up test environment
        await page.goto(process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com');
    });
    
    test('Event management pages load without errors', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        // Wait for redirect to dashboard
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Test event management page
        console.log('Testing event management page...');
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Check for consolidated HVAC Event Manager styles
        const eventWrapper = await page.locator('.hvac-event-wrapper');
        await expect(eventWrapper).toBeVisible();
        
        // Check for TEC Community Events form
        const tecForm = await page.locator('.tribe-community-events-form');
        await expect(tecForm).toBeVisible();
        
        // Verify no JavaScript errors
        const errors = await page.evaluate(() => window.errors || []);
        expect(errors.length).toBe(0);
        
        console.log('✅ Event management page loads correctly');
    });
    
    test('Event edit page functionality', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        // Wait for redirect
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Test edit page with event ID
        console.log('Testing event edit page...');
        await page.goto('/trainer/event/edit/?event_id=1');
        await page.waitForLoadState('networkidle');
        
        // Check for edit wrapper
        const editWrapper = await page.locator('.hvac-edit-event-wrapper');
        await expect(editWrapper).toBeVisible();
        
        // Check for navigation
        const navigation = await page.locator('.hvac-navigation-wrapper');
        if (await navigation.count() > 0) {
            await expect(navigation).toBeVisible();
        }
        
        // Check for breadcrumbs
        const breadcrumbs = await page.locator('.hvac-breadcrumbs-wrapper');
        if (await breadcrumbs.count() > 0) {
            await expect(breadcrumbs).toBeVisible();
        }
        
        console.log('✅ Event edit page loads correctly');
    });
    
    test('HVAC Event Manager class is loaded', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Go to an event page to trigger event manager loading
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Check that consolidated CSS is loaded
        const eventManagerCSS = await page.locator('link[href*="hvac-event-manager.css"]');
        await expect(eventManagerCSS).toHaveCount(1);
        
        // Check that consolidated JS is loaded
        const eventManagerJS = await page.locator('script[src*="hvac-event-manager.js"]');
        await expect(eventManagerJS).toHaveCount(1);
        
        // Verify JavaScript initialization
        const jsInitialized = await page.evaluate(() => {
            return document.querySelector('.hvac-event-wrapper, .hvac-edit-event-wrapper') !== null;
        });
        expect(jsInitialized).toBeTruthy();
        
        console.log('✅ HVAC Event Manager assets loaded correctly');
    });
    
    test('Old event classes are removed', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Go to event page
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Check that old CSS files are NOT loaded
        const oldCSSFiles = [
            'hvac-manage-event.css',
            'hvac-event-edit-fix.css', 
            'hvac-event-edit-comprehensive.css',
            'hvac-custom-event-edit.css'
        ];
        
        for (const cssFile of oldCSSFiles) {
            const oldCSS = await page.locator(`link[href*="${cssFile}"]`);
            await expect(oldCSS).toHaveCount(0);
        }
        
        // Check that old JS files are NOT loaded
        const oldJSFiles = [
            'hvac-event-edit-fix.js',
            'hvac-event-edit-comprehensive.js'
        ];
        
        for (const jsFile of oldJSFiles) {
            const oldJS = await page.locator(`script[src*="${jsFile}"]`);
            await expect(oldJS).toHaveCount(0);
        }
        
        console.log('✅ Old event management assets correctly removed');
    });
    
    test('Shortcodes work correctly', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Test hvac_event_manage shortcode
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Check that shortcode content is rendered
        const shortcodeContent = await page.locator('.tribe-community-events-form');
        await expect(shortcodeContent).toBeVisible();
        
        // Check for proper form elements
        const titleField = await page.locator('input[name*="title"], input[name*="EventTitle"]');
        if (await titleField.count() > 0) {
            await expect(titleField.first()).toBeVisible();
        }
        
        console.log('✅ Event management shortcodes work correctly');
    });
    
    test('Form validation enhancements work', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Go to event creation page
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Wait for JavaScript to initialize
        await page.waitForTimeout(2000);
        
        // Check that form validation JavaScript is working
        const hasValidationJS = await page.evaluate(() => {
            return typeof window.hvac_event_manager !== 'undefined';
        });
        
        // Test form enhancement features
        const titleField = await page.locator('input[name*="title"], input[name*="EventTitle"]').first();
        if (await titleField.count() > 0) {
            // Test placeholder enhancement
            const placeholder = await titleField.getAttribute('placeholder');
            expect(placeholder).toBeTruthy();
        }
        
        console.log('✅ Form validation and enhancements working');
    });
    
    test('Security and authentication work', async ({ page }) => {
        // Test unauthenticated access
        console.log('Testing unauthenticated access...');
        await page.goto('/trainer/event/manage/');
        
        // Should redirect to login
        await page.waitForURL('**/training-login/**');
        expect(page.url()).toContain('training-login');
        
        // Login with proper credentials
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        // Should now access the event management page
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Navigate to event management
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        // Should now see the form
        const eventForm = await page.locator('.tribe-community-events-form');
        await expect(eventForm).toBeVisible();
        
        console.log('✅ Authentication and security working correctly');
    });
    
    test('Performance - page loads efficiently', async ({ page }) => {
        // Login as trainer
        await page.goto('/training-login/');
        await page.fill('input[name="log"]', 'test_trainer');
        await page.fill('input[name="pwd"]', 'TestTrainer123!');
        await page.click('input[type="submit"]');
        
        await page.waitForURL('**/trainer/dashboard/**');
        
        // Measure page load performance
        const startTime = Date.now();
        
        await page.goto('/trainer/event/manage/');
        await page.waitForLoadState('networkidle');
        
        const loadTime = Date.now() - startTime;
        
        // Should load within reasonable time (less than 5 seconds)
        expect(loadTime).toBeLessThan(5000);
        
        // Check that only necessary resources are loaded
        const cssCount = await page.locator('link[rel="stylesheet"]').count();
        const jsCount = await page.locator('script[src]').count();
        
        console.log(`Page loaded in ${loadTime}ms with ${cssCount} CSS files and ${jsCount} JS files`);
        
        // Should have reasonable resource counts (not hundreds like before)
        expect(cssCount).toBeLessThan(50); // Much better than 250+ before
        expect(jsCount).toBeLessThan(20);
        
        console.log('✅ Performance is acceptable');
    });
});

// Run the tests
if (require.main === module) {
    console.log('🚀 Starting HVAC Event Manager Consolidation Tests...');
    console.log('');
    console.log('This test suite verifies that the consolidated event management system:');
    console.log('1. Replaces all 8+ fragmented implementations');
    console.log('2. Maintains all essential functionality'); 
    console.log('3. Improves performance and maintainability');
    console.log('4. Provides proper security and authentication');
    console.log('5. Includes progressive enhancement features');
    console.log('');
}