/**
 * Modernized Trainer Dashboard Test Suite
 * 
 * Demonstrates advanced framework features:
 * - Page Object Model usage
 * - WordPress-specific utilities
 * - Responsive testing
 * - Screenshot management
 * - Test data integration
 * 
 * @package HVAC_Community_Events
 * @version 2.0.0
 * @created 2025-08-27
 * @migrated-from various trainer dashboard tests
 */

const BaseTest = require('../../framework/core/BaseTest');
const TrainerDashboard = require('../../framework/page-objects/TrainerDashboard');
const AuthManager = require('../../framework/core/AuthManager');
const { expect } = require('@playwright/test');

BaseTest.describe('Trainer Dashboard - Modernized', () => {
    let trainerDashboard;
    let authManager;
    
    test.beforeAll(async () => {
        console.log('🚀 Initializing Trainer Dashboard Test Suite');
        authManager = AuthManager;
    });
    
    test.beforeEach(async ({ page }) => {
        trainerDashboard = new TrainerDashboard(page);
    });
    
    BaseTest.create(
        'should display trainer dashboard with all required elements',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing complete dashboard display');
            
            // Authenticate and navigate
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Verify dashboard loads correctly
            await trainerDashboard.verifyDashboard();
            
            // Check essential widgets
            const widgets = ['eventCount', 'upcomingEvents', 'recentActivity'];
            for (const widget of widgets) {
                try {
                    await trainerDashboard.waitForWidget(widget);
                    console.log(`✅ Widget loaded: ${widget}`);
                } catch (error) {
                    console.log(`⚠️ Widget not found: ${widget} - ${error.message}`);
                }
            }
            
            // Verify navigation menu
            await expect(page.locator(trainerDashboard.selectors.navigation)).toBeVisible();
            
            // Verify breadcrumb if present
            if (await trainerDashboard.isVisible(trainerDashboard.selectors.breadcrumb)) {
                await trainerDashboard.verifyBreadcrumbs(['Dashboard']);
            }
            
            // Take screenshot for documentation
            await trainerDashboard.screenshotDashboard();
            
            console.log('✅ Dashboard display verification completed');
        },
        {
            category: 'dashboard',
            priority: 'critical',
            tags: ['trainer', 'dashboard', 'ui'],
            requirements: ['dashboard-display']
        }
    );
    
    BaseTest.create(
        'should provide working navigation to all trainer sections',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing navigation functionality');
            
            // Authenticate and navigate to dashboard
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Test navigation to each section
            const sections = [
                { name: 'events', expectedUrl: '/trainer/events/' },
                { name: 'profile', expectedUrl: '/trainer/profile/' },
                { name: 'venues', expectedUrl: '/trainer/venues/' },
                { name: 'organizers', expectedUrl: '/trainer/organizers/' }
            ];
            
            for (const section of sections) {
                console.log(`🔗 Testing navigation to: ${section.name}`);
                
                try {
                    // Navigate to section
                    await trainerDashboard.navigateToSection(section.name);
                    
                    // Wait for page to load
                    await baseTest.waitForWordPress(page, 'ready');
                    
                    // Verify URL
                    expect(page.url()).toMatch(new RegExp(section.expectedUrl.replace('/', '\\/'), 'i'));
                    
                    // Navigate back to dashboard
                    await trainerDashboard.navigate();
                    
                    console.log(`✅ Navigation to ${section.name} successful`);
                } catch (error) {
                    console.log(`⚠️ Navigation to ${section.name} failed: ${error.message}`);
                    // Continue testing other sections
                }
            }
            
            console.log('✅ Navigation testing completed');
        },
        {
            category: 'dashboard',
            priority: 'high',
            tags: ['trainer', 'navigation', 'ux'],
            requirements: ['trainer-navigation']
        }
    );
    
    BaseTest.create(
        'should display accurate dashboard statistics',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing dashboard statistics accuracy');
            
            // Authenticate and navigate
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Get dashboard statistics
            const stats = await trainerDashboard.getDashboardStats();
            
            console.log('📊 Dashboard Statistics:', stats);
            
            // Verify statistics are valid numbers
            if (stats.eventCount !== undefined) {
                expect(typeof stats.eventCount).toBe('number');
                expect(stats.eventCount).toBeGreaterThanOrEqual(0);
            }
            
            if (stats.upcomingEvents !== undefined) {
                expect(typeof stats.upcomingEvents).toBe('number');
                expect(stats.upcomingEvents).toBeGreaterThanOrEqual(0);
            }
            
            // Cross-verify with actual data by navigating to events page
            try {
                await trainerDashboard.goToManageEvents();
                await baseTest.waitForWordPress(page, 'ready');
                
                // Count actual events on events page
                const actualEventCount = await page.locator('.event-item, .tribe-events-list-event').count();
                
                console.log(`📊 Dashboard showed: ${stats.eventCount}, Events page shows: ${actualEventCount}`);
                
                // Navigate back to dashboard
                await trainerDashboard.navigate();
            } catch (error) {
                console.log('⚠️ Could not verify event count consistency:', error.message);
            }
            
            console.log('✅ Dashboard statistics testing completed');
        },
        {
            category: 'dashboard',
            priority: 'medium',
            tags: ['trainer', 'statistics', 'data'],
            requirements: ['dashboard-statistics']
        }
    );
    
    BaseTest.create(
        'should be responsive across different screen sizes',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing responsive design');
            
            // Authenticate and navigate
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Test mobile responsiveness
            const responsiveness = await trainerDashboard.checkMobileResponsiveness();
            
            console.log('📱 Responsiveness Check:', responsiveness);
            
            // If mobile responsive, test mobile navigation
            if (responsiveness.isMobileResponsive) {
                // Set mobile viewport
                await page.setViewportSize({ width: 375, height: 667 });
                await trainerDashboard.navigate();
                
                // Take mobile screenshot
                await baseTest.takeScreenshot(page, 'trainer-dashboard-mobile', true);
                
                // Test mobile menu if available
                if (responsiveness.hasMobileMenu) {
                    await trainerDashboard.click('.hvac-menu-toggle, .mobile-menu-toggle');
                    await expect(page.locator('.hvac-menu.open, .mobile-menu.open')).toBeVisible();
                }
                
                // Restore desktop viewport
                await page.setViewportSize({ width: 1280, height: 720 });
                await trainerDashboard.navigate();
            }
            
            // Take desktop screenshot for comparison
            await baseTest.takeScreenshot(page, 'trainer-dashboard-desktop', true);
            
            console.log('✅ Responsive design testing completed');
        },
        {
            category: 'dashboard',
            priority: 'medium',
            tags: ['trainer', 'responsive', 'mobile'],
            requirements: ['responsive-design']
        }
    );
    
    BaseTest.create(
        'should handle quick actions correctly',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing quick actions functionality');
            
            // Authenticate and navigate
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Test various quick actions
            const actions = [
                'create-event',
                'edit-profile',
                'view-venues',
                'view-organizers'
            ];
            
            for (const action of actions) {
                console.log(`⚡ Testing quick action: ${action}`);
                
                try {
                    // Navigate to dashboard first
                    await trainerDashboard.navigate();
                    
                    // Perform quick action
                    await trainerDashboard.performQuickAction(action);
                    
                    // Wait for page to load
                    await baseTest.waitForWordPress(page, 'ready');
                    
                    // Verify we navigated somewhere (URL should change)
                    expect(page.url()).not.toMatch(/\/trainer\/dashboard\/$/);
                    
                    console.log(`✅ Quick action ${action} successful`);
                } catch (error) {
                    console.log(`⚠️ Quick action ${action} failed: ${error.message}`);
                    // Continue testing other actions
                }
            }
            
            console.log('✅ Quick actions testing completed');
        },
        {
            category: 'dashboard',
            priority: 'high',
            tags: ['trainer', 'quick-actions', 'ux'],
            requirements: ['dashboard-quick-actions']
        }
    );
    
    BaseTest.create(
        'should display announcements when available',
        async (page, testInfo, baseTest) => {
            console.log('🧪 Testing announcements display');
            
            // Authenticate and navigate
            await authManager.authenticate(page, 'trainer');
            await trainerDashboard.navigate();
            
            // Check for announcements
            const announcementCount = await trainerDashboard.checkAnnouncements();
            
            console.log(`📢 Found ${announcementCount} announcements`);
            
            if (announcementCount > 0) {
                // Test announcement interaction if any exist
                const announcementElements = page.locator('.hvac-announcements .announcement, .trainer-announcements .announcement');
                
                // Verify announcements are visible
                await expect(announcementElements.first()).toBeVisible();
                
                // Test expanding/collapsing if interactive
                try {
                    const expandButton = page.locator('.announcement .expand, .announcement .toggle').first();
                    if (await expandButton.isVisible()) {
                        await expandButton.click();
                        console.log('✅ Announcement expanded successfully');
                    }
                } catch (error) {
                    console.log('ℹ️ Announcements are not interactive');
                }
            }
            
            console.log('✅ Announcements testing completed');
        },
        {
            category: 'dashboard',
            priority: 'medium',
            tags: ['trainer', 'announcements', 'content'],
            requirements: ['dashboard-announcements']
        }
    );
    
    test.afterAll(async () => {
        console.log('✅ Trainer Dashboard Test Suite completed');
        console.log('📊 All dashboard functionality has been verified');
    });
});