/**
 * Help System - Tooltips E2E Tests
 * 
 * Tests the tooltip system functionality including:
 * - Tooltip appearance on hover
 * - Tooltip positioning
 * - Tooltip content accuracy
 * - Cross-page functionality
 */

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

test.describe('Help System - Tooltips @help @tooltips', () => {
    
    test.beforeEach(async ({ page }) => {
        // Login as trainer before each test
        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('Dashboard navigation tooltips appear on hover', async ({ page }) => {
        console.log('Testing dashboard navigation tooltips...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Test Create Event button tooltip
        const createEventButton = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Create Event' });
        await expect(createEventButton).toBeVisible();
        
        // Hover over button
        await createEventButton.hover();
        
        // Wait for tooltip to appear (there's a delay)
        await page.waitForTimeout(600); // Tooltip has 500ms delay
        
        // Check tooltip content
        await expect(createEventButton).toHaveAttribute('data-tooltip', 'Create a new training event with custom pricing and registration options');
        
        console.log('✓ Create Event tooltip works');
        
        // Test My Events button tooltip
        const myEventsButton = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'My Events' });
        await myEventsButton.hover();
        await page.waitForTimeout(600);
        
        await expect(myEventsButton).toHaveAttribute('data-tooltip', 'View and manage all your existing events in one place');
        
        console.log('✓ My Events tooltip works');
        
        // Test Generate Certificates button tooltip
        const certificatesButton = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Generate Certificates' });
        await certificatesButton.hover();
        await page.waitForTimeout(600);
        
        await expect(certificatesButton).toHaveAttribute('data-tooltip', 'Create professional certificates for attendees who completed your training');
        
        console.log('✓ Generate Certificates tooltip works');
        
        await page.screenshot({ path: 'test-results/screenshots/dashboard-tooltips.png' });
    });

    test('Dashboard statistics tooltips work correctly', async ({ page }) => {
        console.log('Testing dashboard statistics tooltips...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Test "Your Stats" section tooltip
        const statsHeader = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Your Stats' });
        if (await statsHeader.count() > 0) {
            await statsHeader.hover();
            await page.waitForTimeout(600);
            
            await expect(statsHeader).toHaveAttribute('data-tooltip', 'Overview of your event performance and revenue metrics');
            console.log('✓ Stats header tooltip works');
        }
        
        // Test individual stat card tooltips
        const statCards = [
            { text: 'Total Events', expectedTooltip: 'All events you\'ve created, including drafts and published events' },
            { text: 'Upcoming Events', expectedTooltip: 'Published events scheduled for future dates' },
            { text: 'Past Events', expectedTooltip: 'Completed events where you can generate certificates' },
            { text: 'Tickets Sold', expectedTooltip: 'Total number of tickets sold across all your events' },
            { text: 'Total Revenue', expectedTooltip: 'Total earnings from all ticket sales (before Stripe fees)' }
        ];
        
        for (const card of statCards) {
            const statElement = page.locator('.hvac-tooltip-wrapper').filter({ hasText: card.text });
            if (await statElement.count() > 0) {
                await statElement.hover();
                await page.waitForTimeout(600);
                
                await expect(statElement).toHaveAttribute('data-tooltip', card.expectedTooltip);
                console.log(`✓ ${card.text} tooltip works`);
            }
        }
        
        await page.screenshot({ path: 'test-results/screenshots/statistics-tooltips.png' });
    });

    test('Events table section tooltips work', async ({ page }) => {
        console.log('Testing events table tooltips...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Test "Your Events" header tooltip
        const eventsHeader = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Your Events' });
        if (await eventsHeader.count() > 0) {
            await eventsHeader.hover();
            await page.waitForTimeout(600);
            
            await expect(eventsHeader).toHaveAttribute('data-tooltip', 'Detailed view of all your events with performance metrics and management options');
            console.log('✓ Events header tooltip works');
        }
        
        // Test filter tooltip
        const filterElement = page.locator('.hvac-tooltip-wrapper').filter({ hasText: 'Filter:' });
        if (await filterElement.count() > 0) {
            await filterElement.hover();
            await page.waitForTimeout(600);
            
            await expect(filterElement).toHaveAttribute('data-tooltip', 'Filter events by their publication status');
            console.log('✓ Filter tooltip works');
        }
        
        await page.screenshot({ path: 'test-results/screenshots/events-table-tooltips.png' });
    });

    test('Tooltip positioning works correctly', async ({ page }) => {
        console.log('Testing tooltip positioning...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Find tooltips with different position attributes
        const topTooltip = page.locator('.hvac-tooltip-wrapper[data-position="top"]').first();
        const bottomTooltip = page.locator('.hvac-tooltip-wrapper[data-position="bottom"]').first();
        
        if (await topTooltip.count() > 0) {
            await expect(topTooltip).toHaveAttribute('data-position', 'top');
            console.log('✓ Top positioned tooltip found');
        }
        
        if (await bottomTooltip.count() > 0) {
            await expect(bottomTooltip).toHaveAttribute('data-position', 'bottom');
            console.log('✓ Bottom positioned tooltip found');
        }
        
        // Test default positioning (should default to top if not specified)
        const defaultTooltip = page.locator('.hvac-tooltip-wrapper').not('[data-position]').first();
        if (await defaultTooltip.count() > 0) {
            console.log('✓ Default positioned tooltip found');
        }
    });

    test('Tooltips work on trainer profile page', async ({ page }) => {
        console.log('Testing tooltips on trainer profile page...');
        
        await page.goto(PATHS.profile);
        await page.waitForLoadState('networkidle');
        
        // Check if help button is present with tooltip
        const helpButton = page.locator('a').filter({ hasText: 'Help' });
        await expect(helpButton).toBeVisible();
        
        // Test any tooltips that might be on the profile page
        const tooltipElements = page.locator('.hvac-tooltip-wrapper');
        const tooltipCount = await tooltipElements.count();
        
        if (tooltipCount > 0) {
            console.log(`Found ${tooltipCount} tooltip elements on profile page`);
            
            // Test the first tooltip
            await tooltipElements.first().hover();
            await page.waitForTimeout(600);
            
            // Verify it has a data-tooltip attribute
            await expect(tooltipElements.first()).toHaveAttribute('data-tooltip');
        }
        
        console.log('✓ Profile page tooltips checked');
        await page.screenshot({ path: 'test-results/screenshots/profile-tooltips.png' });
    });

    test('Tooltip CSS classes are applied correctly', async ({ page }) => {
        console.log('Testing tooltip CSS classes...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Check if tooltip wrapper elements have the correct classes
        const tooltipWrappers = page.locator('.hvac-tooltip-wrapper');
        const count = await tooltipWrappers.count();
        
        expect(count).toBeGreaterThan(0);
        console.log(`Found ${count} tooltip wrapper elements`);
        
        // Check that each wrapper has the required attributes
        for (let i = 0; i < Math.min(count, 5); i++) { // Test first 5 tooltips
            const wrapper = tooltipWrappers.nth(i);
            
            // Should have hvac-tooltip-wrapper class
            await expect(wrapper).toHaveClass(/hvac-tooltip-wrapper/);
            
            // Should have data-tooltip attribute
            await expect(wrapper).toHaveAttribute('data-tooltip');
            
            console.log(`✓ Tooltip ${i + 1} has correct attributes`);
        }
    });

    test('Tooltips disappear when not hovering', async ({ page }) => {
        console.log('Testing tooltip hover behavior...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        const tooltipElement = page.locator('.hvac-tooltip-wrapper').first();
        
        // Hover over element
        await tooltipElement.hover();
        await page.waitForTimeout(600);
        
        // Move mouse away
        await page.mouse.move(0, 0);
        await page.waitForTimeout(200);
        
        // Tooltip should not be visible (this is handled by CSS)
        // We can verify the hover state is removed by checking computed styles
        console.log('✓ Tooltip hover behavior tested');
    });

    test('Help system CSS and JS are loaded', async ({ page }) => {
        console.log('Testing help system assets loading...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Check if help system CSS is loaded
        const helpSystemCSS = await page.locator('link[href*="hvac-help-system.css"]').count();
        expect(helpSystemCSS).toBeGreaterThan(0);
        console.log('✓ Help system CSS is loaded');
        
        // Check if help system JS is loaded
        const helpSystemJS = await page.locator('script[src*="hvac-help-system.js"]').count();
        expect(helpSystemJS).toBeGreaterThan(0);
        console.log('✓ Help system JS is loaded');
        
        // Check if Font Awesome is loaded for icons
        const fontAwesome = await page.locator('link[href*="font-awesome"]').count();
        expect(fontAwesome).toBeGreaterThan(0);
        console.log('✓ Font Awesome is loaded');
    });

    test('Tooltip functionality works with JavaScript', async ({ page }) => {
        console.log('Testing tooltip JavaScript functionality...');
        
        await page.goto(PATHS.dashboard);
        await page.waitForLoadState('networkidle');
        
        // Check if the HVACHelp object is available in the global scope
        const hvacHelpExists = await page.evaluate(() => {
            return typeof window.HVACHelp !== 'undefined';
        });
        
        expect(hvacHelpExists).toBe(true);
        console.log('✓ HVACHelp JavaScript object is available');
        
        // Test the addTooltip function
        const tooltipAdded = await page.evaluate(() => {
            const testElement = document.createElement('span');
            testElement.id = 'test-tooltip-element';
            testElement.textContent = 'Test Element';
            document.body.appendChild(testElement);
            
            window.HVACHelp.addTooltip('#test-tooltip-element', 'Test tooltip text', 'top');
            
            const element = document.getElementById('test-tooltip-element');
            return element.classList.contains('hvac-tooltip-wrapper') && 
                   element.getAttribute('data-tooltip') === 'Test tooltip text';
        });
        
        expect(tooltipAdded).toBe(true);
        console.log('✓ JavaScript addTooltip function works');
    });
});