/**
 * Help System - Integration E2E Tests
 * 
 * Tests the complete help system integration including:
 * - End-to-end user journey through help features
 * - Cross-page functionality
 * - Cookie persistence
 * - Complete help system workflow
 */

import { test, expect } from '@playwright/test';
import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';

test.describe('Help System - Integration Tests @help @integration', () => {
    
    test('Complete help system user journey', async ({ page, context }) => {
        console.log('Testing complete help system user journey...');
        
        // Clear cookies for fresh experience
        await context.clearCookies();
        
        // 1. Login and see welcome guide
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Welcome guide should appear
        await expect(page.locator('#hvac-welcome-modal')).toBeVisible();
        console.log('✓ Step 1: Welcome guide appears on first visit');
        
        // 2. Navigate through welcome guide
        await page.click('#hvac-next-card');
        await page.click('#hvac-next-card');
        await page.click('#hvac-next-card');
        
        // Complete the welcome guide
        await page.check('#hvac-dont-show-again');
        await page.click('#hvac-get-started');
        
        // Modal should disappear
        await expect(page.locator('#hvac-welcome-modal')).not.toBeVisible();
        console.log('✓ Step 2: Welcome guide navigation and dismissal works');
        
        // 3. Test tooltips on dashboard
        const createEventTooltip = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Create Event' });
        if (await createEventTooltip.count() > 0) {
            await createEventTooltip.hover();
            await page.waitForTimeout(600);
            console.log('✓ Step 3: Dashboard tooltips work');
        }
        
        // 4. Navigate to documentation via help button
        const helpButton = page.locator('a').filter({ hasText: 'Help' });
        if (await helpButton.count() > 0) {
            await helpButton.click();
            await page.waitForLoadState('networkidle');
            
            await expect(page).toHaveURL(/hvac-documentation/);
            await expect(page.locator('h1')).toContainText('Trainer Documentation');
            console.log('✓ Step 4: Navigation to documentation works');
        }
        
        // 5. Test documentation navigation
        const faqLink = page.locator('.hvac-doc-link[href="#faq"]');
        await faqLink.click();
        await page.waitForTimeout(1000);
        
        const faqSection = page.locator('#faq');
        await expect(faqSection).toBeInViewport();
        console.log('✓ Step 5: Documentation navigation works');
        
        // 6. Return to dashboard and verify welcome guide doesn't show
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        await expect(page.locator('#hvac-welcome-modal')).not.toBeVisible();
        console.log('✓ Step 6: Welcome guide stays dismissed');
        
        // 7. Visit profile page and check help button
        await page.goto(PATHS.profile);
        await page.waitForLoadState('networkidle');
        
        const profileHelpButton = page.locator('a').filter({ hasText: 'Help' });
        await expect(profileHelpButton).toBeVisible();
        console.log('✓ Step 7: Help button available on profile page');
        
        await page.screenshot({ path: 'test-results/screenshots/help-system-integration.png' });
        console.log('✓ Complete help system user journey successful');
    });

    test('Help system works across multiple sessions', async ({ page, context }) => {
        console.log('Testing help system persistence across sessions...');
        
        // Session 1: Dismiss welcome guide
        await context.clearCookies();
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        await expect(page.locator('#hvac-welcome-modal')).toBeVisible();
        
        // Dismiss permanently
        await page.check('#hvac-dont-show-again');
        await page.click('#hvac-get-started');
        
        console.log('✓ Session 1: Welcome guide dismissed');
        
        // Session 2: Create new page context (simulates new session)
        const newContext = await page.context().browser()?.newContext();
        if (newContext) {
            const newPage = await newContext.newPage();
            
            // Copy cookies from original context
            const cookies = await context.cookies();
            await newContext.addCookies(cookies);
            
            await newPage.goto(PATHS.login);
            await newPage.fill('#user_login', 'test_trainer');
            await newPage.fill('#user_pass', 'Test123!');
            await newPage.click('#wp-submit');
            await newPage.waitForLoadState('networkidle');
            
            await newPage.goto(PATHS.dashboard);
            await newPage.waitForLoadState('networkidle');
            
            // Welcome guide should NOT appear
            await expect(newPage.locator('#hvac-welcome-modal')).not.toBeVisible();
            console.log('✓ Session 2: Welcome guide stays dismissed');
            
            await newContext.close();
        }
    });

    test('Help system accessibility features work', async ({ page }) => {
        console.log('Testing help system accessibility...');
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Test keyboard navigation if welcome guide appears
        const welcomeModal = page.locator('#hvac-welcome-modal');
        if (await welcomeModal.isVisible()) {
            // Test tab navigation
            await page.keyboard.press('Tab');
            
            // Test arrow key navigation
            await page.keyboard.press('ArrowRight');
            await page.keyboard.press('ArrowLeft');
            
            // Test escape key
            await page.keyboard.press('Escape');
            await expect(welcomeModal).not.toBeVisible();
            
            console.log('✓ Welcome guide keyboard accessibility works');
        }
        
        // Test tooltip accessibility
        const tooltipElements = page.locator('.hvac-tooltip-wrapper');
        const count = await tooltipElements.count();
        
        if (count > 0) {
            // Check first tooltip has proper attributes
            await expect(tooltipElements.first()).toHaveAttribute('data-tooltip');
            console.log('✓ Tooltip accessibility attributes present');
        }
    });

    test('Help system performance and loading', async ({ page }) => {
        console.log('Testing help system performance...');
        
        // Measure page load time with help system
        const startTime = Date.now();
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        const loadTime = Date.now() - startTime;
        console.log(`Page load time with help system: ${loadTime}ms`);
        
        // Check that help system assets are loaded
        const helpCSS = await page.locator('link[href*="hvac-help-system.css"]').count();
        const helpJS = await page.locator('script[src*="hvac-help-system.js"]').count();
        const fontAwesome = await page.locator('link[href*="font-awesome"]').count();
        
        expect(helpCSS).toBeGreaterThan(0);
        expect(helpJS).toBeGreaterThan(0);
        expect(fontAwesome).toBeGreaterThan(0);
        
        console.log('✓ All help system assets loaded correctly');
        
        // Test JavaScript functionality
        const hvacHelpAvailable = await page.evaluate(() => {
            return typeof window.HVACHelp !== 'undefined';
        });
        
        expect(hvacHelpAvailable).toBe(true);
        console.log('✓ Help system JavaScript initialized');
    });

    test('Help system error handling', async ({ page }) => {
        console.log('Testing help system error handling...');
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        // Test accessing documentation page directly
        await page.goto(`${STAGING_URL}/hvac-documentation/`);
        await page.waitForLoadState('networkidle');
        
        // Should load successfully for authenticated users
        await expect(page.locator('h1')).toContainText('Trainer Documentation');
        console.log('✓ Documentation page loads for authenticated users');
        
        // Test help system with disabled JavaScript
        await page.context().addInitScript(() => {
            // Simulate JS error scenario
            window.addEventListener('error', (e) => {
                console.log('JavaScript error handled:', e.message);
            });
        });
        
        await page.reload();
        await page.waitForLoadState('networkidle');
        
        // Page should still be functional even if JS fails
        await expect(page.locator('h1')).toContainText('Trainer Documentation');
        console.log('✓ Help system gracefully handles JS errors');
    });

    test('Help system AJAX functionality', async ({ page }) => {
        console.log('Testing help system AJAX functionality...');
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Monitor network requests
        const requests: any[] = [];
        page.on('request', request => {
            if (request.url().includes('admin-ajax.php')) {
                requests.push(request);
            }
        });
        
        // If welcome guide appears, test AJAX dismissal
        const welcomeModal = page.locator('#hvac-welcome-modal');
        if (await welcomeModal.isVisible()) {
            await page.check('#hvac-dont-show-again');
            await page.click('#hvac-get-started');
            
            // Wait for AJAX request
            await page.waitForTimeout(2000);
            
            // Check if AJAX request was made
            const ajaxRequests = requests.filter(req => 
                req.postData() && req.postData().includes('hvac_dismiss_welcome')
            );
            
            if (ajaxRequests.length > 0) {
                console.log('✓ AJAX dismissal request sent');
            }
        }
        
        console.log('✓ Help system AJAX functionality tested');
    });

    test('Help system mobile responsiveness', async ({ page }) => {
        console.log('Testing help system mobile responsiveness...');
        
        // Set mobile viewport
        await page.setViewportSize({ width: 375, height: 667 });
        
        await page.goto(PATHS.login);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Test welcome guide on mobile
        const welcomeModal = page.locator('#hvac-welcome-modal');
        if (await welcomeModal.isVisible()) {
            // Check modal is properly sized for mobile
            await expect(welcomeModal).toBeVisible();
            
            // Test navigation on mobile
            await page.click('#hvac-next-card');
            await page.click('#hvac-get-started');
            
            console.log('✓ Welcome guide works on mobile');
        }
        
        // Test documentation page on mobile
        await page.goto(`${STAGING_URL}/hvac-documentation/`);
        await page.waitForLoadState('networkidle');
        
        await expect(page.locator('.hvac-documentation')).toBeVisible();
        
        // Test navigation menu on mobile
        const navMenu = page.locator('.hvac-doc-nav');
        await expect(navMenu).toBeVisible();
        
        console.log('✓ Documentation page works on mobile');
        await page.screenshot({ path: 'test-results/screenshots/help-system-mobile.png' });
    });
});