/**
 * UX Enhancements Verification Test
 * 
 * Verifies that all UX enhancements are deployed and working correctly
 */

import { test, expect } from '@playwright/test';

const STAGING_URL = 'https://upskill-staging.measurequick.com';

test.describe('UX Enhancements Verification', () => {
    test('Verify UX assets are loaded and functional', async ({ page }) => {
        test.setTimeout(25000);

        // Login first
        await page.goto(`${STAGING_URL}/community-login`);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        // Verify we're on dashboard
        await expect(page).toHaveURL(/hvac-dashboard/);

        // Check that UX enhancement JavaScript is loaded
        const uxStatus = await page.evaluate(() => {
            // Check if our UX enhancement objects are available
            const hasHVACToast = typeof window.HVACToast !== 'undefined';
            const hasHVACLoading = typeof window.HVACLoading !== 'undefined';
            const hasHVACAjax = typeof window.HVACAjax !== 'undefined';
            
            // Check if toast functionality works
            let toastWorks = false;
            if (hasHVACToast) {
                try {
                    // Test creating a toast
                    const toastId = window.HVACToast.success('Test toast for verification');
                    toastWorks = !!toastId;
                } catch (e) {
                    toastWorks = false;
                }
            }

            // Check if UX CSS is loaded by looking for specific classes
            const uxStyles = Array.from(document.styleSheets).some(sheet => {
                try {
                    return Array.from(sheet.cssRules).some(rule => 
                        rule.selectorText && (
                            rule.selectorText.includes('hvac-toast') ||
                            rule.selectorText.includes('hvac-loading') ||
                            rule.selectorText.includes('hvac-spinner')
                        )
                    );
                } catch (e) {
                    return false;
                }
            });

            return {
                hasHVACToast,
                hasHVACLoading,
                hasHVACAjax,
                toastWorks,
                uxStyles,
                userAgent: navigator.userAgent
            };
        });

        console.log('UX Enhancement Status:', uxStatus);

        // Verify core UX objects are loaded
        expect(uxStatus.hasHVACToast).toBe(true);
        expect(uxStatus.hasHVACLoading).toBe(true);
        expect(uxStatus.hasHVACAjax).toBe(true);
        expect(uxStatus.toastWorks).toBe(true);

        // Check if toast is visible
        const toast = page.locator('.hvac-toast');
        await expect(toast).toBeVisible();

        await page.screenshot({ path: 'test-results/ux-enhancements-working.png' });
    });

    test('Test toast notification functionality', async ({ page }) => {
        test.setTimeout(20000);

        // Login
        await page.goto(`${STAGING_URL}/community-login`);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        // Create different types of toasts
        await page.evaluate(() => {
            if (window.HVACToast) {
                window.HVACToast.success('Success message test');
                window.HVACToast.error('Error message test');
                window.HVACToast.warning('Warning message test');
                window.HVACToast.info('Info message test');
            }
        });

        await page.waitForTimeout(1000);

        // Check if toasts are visible
        const toasts = page.locator('.hvac-toast');
        const toastCount = await toasts.count();
        expect(toastCount).toBeGreaterThan(0);

        // Check different toast types exist
        const successToast = page.locator('.hvac-toast.success');
        const errorToast = page.locator('.hvac-toast.error');
        
        await expect(successToast).toBeVisible();
        await expect(errorToast).toBeVisible();

        await page.screenshot({ path: 'test-results/toast-notifications-working.png' });
    });

    test('Test mobile responsiveness', async ({ page }) => {
        test.setTimeout(20000);

        // Set mobile viewport
        await page.setViewportSize({ width: 375, height: 667 });

        // Login
        await page.goto(`${STAGING_URL}/community-login`);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        // Check page is responsive
        const viewport = page.viewportSize();
        expect(viewport?.width).toBe(375);
        expect(viewport?.height).toBe(667);

        // Check dashboard is visible
        const dashboardContent = page.locator('body');
        await expect(dashboardContent).toBeVisible();

        // Check form elements are touch-friendly (test button size)
        const navLinks = page.locator('a[href*="hvac-dashboard"], a[href*="manage-event"]');
        if (await navLinks.count() > 0) {
            const firstLink = navLinks.first();
            const linkBox = await firstLink.boundingBox();
            if (linkBox) {
                // Touch targets should be at least 40px for good mobile UX
                expect(linkBox.height).toBeGreaterThanOrEqual(40);
            }
        }

        await page.screenshot({ path: 'test-results/mobile-responsive-375.png' });
    });

    test('Test loading states functionality', async ({ page }) => {
        test.setTimeout(20000);

        // Login
        await page.goto(`${STAGING_URL}/community-login`);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        // Test loading functionality
        const loadingWorks = await page.evaluate(() => {
            if (window.HVACLoading) {
                // Test button loading state
                const testButton = document.createElement('button');
                testButton.id = 'test-loading-btn';
                testButton.textContent = 'Test Button';
                document.body.appendChild(testButton);

                // Apply loading state
                window.HVACLoading.showButton(testButton, 'Testing...');
                
                const isLoading = testButton.classList.contains('loading');
                const isDisabled = testButton.disabled;
                
                // Clean up
                window.HVACLoading.hideButton(testButton);
                testButton.remove();
                
                return { isLoading, isDisabled, hasHVACLoading: true };
            }
            return { hasHVACLoading: false };
        });

        expect(loadingWorks.hasHVACLoading).toBe(true);
        expect(loadingWorks.isLoading).toBe(true);
        expect(loadingWorks.isDisabled).toBe(true);

        await page.screenshot({ path: 'test-results/loading-states-working.png' });
    });

    test('Verify all pages load UX enhancements', async ({ page }) => {
        test.setTimeout(30000);

        // Login
        await page.goto(`${STAGING_URL}/community-login`);
        await page.fill('#user_login', 'test_trainer');
        await page.fill('#user_pass', 'Test123!');
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        const pagesToTest = [
            { url: '/hvac-dashboard/', name: 'Dashboard' },
            { url: '/manage-event/', name: 'Create Event' },
            { url: '/generate-certificates/', name: 'Generate Certificates' },
            { url: '/trainer-profile/', name: 'Trainer Profile' }
        ];

        for (const pageTest of pagesToTest) {
            await page.goto(`${STAGING_URL}${pageTest.url}`);
            await page.waitForLoadState('networkidle');

            // Check if UX enhancements are loaded on this page
            const hasUX = await page.evaluate(() => {
                return typeof window.HVACToast !== 'undefined' || 
                       typeof window.HVACLoading !== 'undefined';
            });

            console.log(`${pageTest.name}: UX enhancements loaded = ${hasUX}`);
            
            // At least dashboard and certificate pages should have UX enhancements
            if (pageTest.url.includes('dashboard') || pageTest.url.includes('certificate')) {
                expect(hasUX).toBe(true);
            }
        }
    });
});