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

test.describe('UI Styling Review - Full Page Screenshots', () => {
  const pages = [
    { name: 'Community Login', url: '/community-login' },
    { name: 'HVAC Dashboard', url: '/hvac-dashboard' },
    { name: 'Generate Certificates', url: '/generate-certificates' },
    { name: 'Certificate Reports', url: '/certificate-reports' },
    { name: 'Trainer Profile', url: '/trainer-profile' },
    { name: 'My Events', url: '/my-events' },
    { name: 'Create Event', url: '/create-event' },
    { name: 'Event Summary', url: '/event-summary' },
    { name: 'Email Attendees', url: '/email-attendees' }
  ];

  // Test logged out states
  test('Screenshot all pages - Logged Out', async ({ page }) => {
    console.log('=== Taking Screenshots of All Pages (Logged Out) ===');
    
    for (const pageInfo of pages) {
      try {
        console.log(`📸 Capturing: ${pageInfo.name} (${pageInfo.url})`);
        
        await page.goto(`https://upskill-staging.measurequick.com${pageInfo.url}`, { 
          waitUntil: 'networkidle',
          timeout: 30000 
        });
        
        // Wait for page to fully load
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(2000);
        
        // Take full page screenshot
        await page.screenshot({ 
          path: `test-results/ui-review-${pageInfo.name.toLowerCase().replace(/\s+/g, '-')}-logged-out.png`,
          fullPage: true 
        });
        
        console.log(`✅ Captured: ${pageInfo.name}`);
      } catch (error) {
        console.log(`⚠️ Failed to capture ${pageInfo.name}: ${error.message}`);
      }
    }
  });

  // Test logged in states
  test('Screenshot all pages - Logged In', async ({ page }) => {
    console.log('=== Taking Screenshots of All Pages (Logged In) ===');
    
    // Login first
    await page.goto('https://upskill-staging.measurequick.com/community-login');
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    await page.waitForURL('**/hvac-dashboard/**');
    await page.waitForLoadState('networkidle');
    
    console.log('✅ Logged in successfully');
    
    for (const pageInfo of pages) {
      try {
        console.log(`📸 Capturing: ${pageInfo.name} (${pageInfo.url})`);
        
        await page.goto(`https://upskill-staging.measurequick.com${pageInfo.url}`, { 
          waitUntil: 'networkidle',
          timeout: 30000 
        });
        
        // Wait for page to fully load
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(2000);
        
        // Special handling for pages with dynamic content
        if (pageInfo.name === 'Generate Certificates') {
          // Try to select an event to show the full interface
          const eventSelector = page.locator('#event_id');
          if (await eventSelector.isVisible()) {
            const options = await eventSelector.locator('option:not([value=""])').count();
            if (options > 0) {
              await eventSelector.selectOption({ index: 1 });
              await page.waitForTimeout(2000); // Wait for AJAX
            }
          }
        }
        
        if (pageInfo.name === 'Event Summary') {
          // Try to find any event to view
          const eventLinks = page.locator('a[href*="/event-summary/"]');
          const linkCount = await eventLinks.count();
          if (linkCount > 0) {
            await eventLinks.first().click();
            await page.waitForLoadState('networkidle');
            await page.waitForTimeout(2000);
          }
        }
        
        // Take full page screenshot
        await page.screenshot({ 
          path: `test-results/ui-review-${pageInfo.name.toLowerCase().replace(/\s+/g, '-')}-logged-in.png`,
          fullPage: true 
        });
        
        console.log(`✅ Captured: ${pageInfo.name}`);
      } catch (error) {
        console.log(`⚠️ Failed to capture ${pageInfo.name}: ${error.message}`);
        
        // Take screenshot anyway to see error state
        try {
          await page.screenshot({ 
            path: `test-results/ui-review-${pageInfo.name.toLowerCase().replace(/\s+/g, '-')}-error.png`,
            fullPage: true 
          });
        } catch (screenshotError) {
          console.log(`❌ Could not take error screenshot: ${screenshotError.message}`);
        }
      }
    }
  });

  // Test WordPress theme analysis
  test('Analyze WordPress Theme Styling', async ({ page }) => {
    console.log('=== Analyzing WordPress Theme Styling ===');
    
    // Go to homepage to analyze theme
    await page.goto('https://upskill-staging.measurequick.com/', { waitUntil: 'networkidle' });
    
    // Extract theme colors, fonts, and styling
    const themeAnalysis = await page.evaluate(() => {
      const computedStyle = getComputedStyle(document.body);
      const headerStyle = getComputedStyle(document.querySelector('h1, .site-title, header') || document.body);
      const linkStyle = getComputedStyle(document.querySelector('a') || document.body);
      
      return {
        bodyFont: computedStyle.fontFamily,
        bodyFontSize: computedStyle.fontSize,
        bodyColor: computedStyle.color,
        bodyBackground: computedStyle.backgroundColor,
        headerFont: headerStyle.fontFamily,
        headerColor: headerStyle.color,
        linkColor: linkStyle.color,
        primaryColor: getComputedStyle(document.documentElement).getPropertyValue('--wp--preset--color--primary') || 'not-set',
        secondaryColor: getComputedStyle(document.documentElement).getPropertyValue('--wp--preset--color--secondary') || 'not-set'
      };
    });
    
    console.log('🎨 WordPress Theme Analysis:', themeAnalysis);
    
    // Take homepage screenshot
    await page.screenshot({ 
      path: 'test-results/ui-review-wordpress-homepage.png',
      fullPage: true 
    });
    
    console.log('✅ WordPress theme analysis complete');
  });

  // Test mobile responsiveness
  test('Mobile Responsiveness Check', async ({ page }) => {
    console.log('=== Mobile Responsiveness Check ===');
    
    // Set mobile viewport
    await page.setViewportSize({ width: 375, height: 667 }); // iPhone SE
    
    // Login
    await page.goto('https://upskill-staging.measurequick.com/community-login');
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    await page.waitForURL('**/hvac-dashboard/**');
    await page.waitForLoadState('networkidle');
    
    // Test key pages on mobile
    const mobilePages = [
      { name: 'Dashboard', url: '/hvac-dashboard' },
      { name: 'Generate Certificates', url: '/generate-certificates' },
      { name: 'Certificate Reports', url: '/certificate-reports' }
    ];
    
    for (const pageInfo of mobilePages) {
      try {
        console.log(`📱 Mobile test: ${pageInfo.name}`);
        
        await page.goto(`https://upskill-staging.measurequick.com${pageInfo.url}`, { 
          waitUntil: 'networkidle' 
        });
        await page.waitForTimeout(2000);
        
        await page.screenshot({ 
          path: `test-results/ui-review-${pageInfo.name.toLowerCase().replace(/\s+/g, '-')}-mobile.png`,
          fullPage: true 
        });
        
        console.log(`✅ Mobile captured: ${pageInfo.name}`);
      } catch (error) {
        console.log(`⚠️ Mobile test failed for ${pageInfo.name}: ${error.message}`);
      }
    }
  });
});