const { chromium } = require('playwright');
const fs = require('fs');

async function testLoginPage() {
  const browser = await chromium.launch({ 
    headless: false,
    slowMo: 1000 // Slow down actions for better observation
  });
  
  const context = await browser.newContext({
    viewport: { width: 1200, height: 800 },
    recordVideo: {
      dir: 'test-recordings/',
      size: { width: 1200, height: 800 }
    }
  });
  
  const page = await context.newPage();
  
  // Listen for console messages and errors
  const consoleMessages = [];
  const networkErrors = [];
  
  page.on('console', msg => {
    consoleMessages.push(`${msg.type()}: ${msg.text()}`);
    console.log(`Console ${msg.type()}: ${msg.text()}`);
  });
  
  page.on('requestfailed', request => {
    networkErrors.push(`Failed: ${request.url()} - ${request.failure().errorText}`);
    console.log(`Network Error: ${request.url()} - ${request.failure().errorText}`);
  });

  try {
    console.log('=== QA AUDIT: LOGIN PAGE TESTING ===\n');
    
    // Test 1: Navigate to login-new page
    console.log('1. Navigating to http://localhost:3001/login-new...');
    await page.goto('http://localhost:3001/login-new', { waitUntil: 'networkidle' });
    
    // Take initial screenshot
    await page.screenshot({ path: 'login-page.png', fullPage: true });
    console.log('✓ Screenshot saved as login-page.png');
    
    // Test 2: Check if page loaded correctly
    const title = await page.title();
    console.log(`✓ Page title: ${title}`);
    
    // Test 3: Check for form fields
    console.log('\n2. Testing form elements...');
    
    const emailField = await page.locator('input[type="email"], input[name="email"], input[id="email"]').first();
    const passwordField = await page.locator('input[type="password"], input[name="password"], input[id="password"]').first();
    const submitButton = await page.locator('button[type="submit"], input[type="submit"], button:has-text("Login"), button:has-text("Sign In")').first();
    
    const emailExists = await emailField.count() > 0;
    const passwordExists = await passwordField.count() > 0;
    const submitExists = await submitButton.count() > 0;
    
    console.log(`✓ Email field present: ${emailExists}`);
    console.log(`✓ Password field present: ${passwordExists}`);
    console.log(`✓ Submit button present: ${submitExists}`);
    
    if (!emailExists || !passwordExists || !submitExists) {
      console.log('❌ Missing essential form elements!');
      
      // Debug: List all form elements
      const allInputs = await page.locator('input').all();
      console.log('\nAll input elements found:');
      for (let input of allInputs) {
        const type = await input.getAttribute('type');
        const name = await input.getAttribute('name');
        const id = await input.getAttribute('id');
        const placeholder = await input.getAttribute('placeholder');
        console.log(`  - Type: ${type}, Name: ${name}, ID: ${id}, Placeholder: ${placeholder}`);
      }
      
      const allButtons = await page.locator('button').all();
      console.log('\nAll button elements found:');
      for (let button of allButtons) {
        const type = await button.getAttribute('type');
        const text = await button.textContent();
        console.log(`  - Type: ${type}, Text: ${text}`);
      }
    }
    
    // Test 4: Accessibility testing
    console.log('\n3. Testing accessibility...');
    
    if (emailExists) {
      const emailLabel = await emailField.getAttribute('aria-label') || 
                         await page.locator(`label[for="${await emailField.getAttribute('id')}"]`).textContent() ||
                         await emailField.getAttribute('placeholder');
      console.log(`✓ Email field label/aria-label: ${emailLabel}`);
    }
    
    if (passwordExists) {
      const passwordLabel = await passwordField.getAttribute('aria-label') || 
                           await page.locator(`label[for="${await passwordField.getAttribute('id')}"]`).textContent() ||
                           await passwordField.getAttribute('placeholder');
      console.log(`✓ Password field label/aria-label: ${passwordLabel}`);
    }
    
    // Test tab navigation
    await page.keyboard.press('Tab');
    await page.waitForTimeout(500);
    const firstFocused = await page.evaluate(() => document.activeElement?.tagName);
    
    await page.keyboard.press('Tab');
    await page.waitForTimeout(500);
    const secondFocused = await page.evaluate(() => document.activeElement?.tagName);
    
    console.log(`✓ Tab navigation: ${firstFocused} → ${secondFocused}`);
    
    // Test 5: Form validation
    console.log('\n4. Testing form validation...');
    
    if (submitExists) {
      // Try submitting empty form
      await submitButton.click();
      await page.waitForTimeout(2000);
      
      // Check for validation messages
      const validationMessages = await page.locator('[role="alert"], .error, .invalid, [aria-invalid="true"]').all();
      console.log(`✓ Validation messages found: ${validationMessages.length}`);
      
      for (let msg of validationMessages) {
        const text = await msg.textContent();
        console.log(`  - Validation: ${text}`);
      }
      
      // Screenshot after validation attempt
      await page.screenshot({ path: 'login-validation.png', fullPage: true });
      console.log('✓ Validation screenshot saved as login-validation.png');
    }
    
    // Test 6: Try valid login attempt (if fields exist)
    if (emailExists && passwordExists && submitExists) {
      console.log('\n5. Testing login with test credentials...');
      
      await emailField.fill('test@example.com');
      await passwordField.fill('testpassword123');
      
      // Screenshot with filled form
      await page.screenshot({ path: 'login-form-filled.png', fullPage: true });
      console.log('✓ Filled form screenshot saved');
      
      await submitButton.click();
      await page.waitForTimeout(3000);
      
      // Check if redirected or if there's an error
      const currentURL = page.url();
      console.log(`✓ Current URL after login attempt: ${currentURL}`);
      
      // Check for error messages
      const errorElements = await page.locator('.error, [role="alert"], .alert-error').all();
      for (let error of errorElements) {
        const text = await error.textContent();
        console.log(`  - Error message: ${text}`);
      }
      
      // Screenshot after login attempt
      await page.screenshot({ path: 'login-after-attempt.png', fullPage: true });
    }
    
    // Test 7: Test other auth pages
    console.log('\n6. Testing other authentication pages...');
    
    const authPages = [
      '/login',
      '/dashboard', 
      '/auth-status',
      '/auth-demo'
    ];
    
    for (const authPage of authPages) {
      try {
        console.log(`\nTesting ${authPage}...`);
        await page.goto(`http://localhost:3001${authPage}`, { waitUntil: 'networkidle' });
        
        const pageTitle = await page.title();
        const hasError = await page.locator('text=404, text=Error, text=Not Found').count() > 0;
        
        console.log(`  ✓ ${authPage} - Title: ${pageTitle}, Has Error: ${hasError}`);
        
        // Take screenshot of each auth page
        const filename = `auth-page${authPage.replace('/', '-')}.png`;
        await page.screenshot({ path: filename, fullPage: true });
        console.log(`  ✓ Screenshot saved: ${filename}`);
        
      } catch (error) {
        console.log(`  ❌ ${authPage} - Error: ${error.message}`);
      }
    }
    
    // Test 8: Report summary
    console.log('\n=== QA AUDIT SUMMARY ===');
    console.log(`Console messages: ${consoleMessages.length}`);
    console.log(`Network errors: ${networkErrors.length}`);
    
    if (consoleMessages.length > 0) {
      console.log('\nConsole Messages:');
      consoleMessages.forEach(msg => console.log(`  ${msg}`));
    }
    
    if (networkErrors.length > 0) {
      console.log('\nNetwork Errors:');
      networkErrors.forEach(error => console.log(`  ${error}`));
    }
    
    // Save detailed report
    const report = {
      timestamp: new Date().toISOString(),
      loginPageTest: {
        url: 'http://localhost:3001/login-new',
        formElements: {
          emailField: emailExists,
          passwordField: passwordExists,
          submitButton: submitExists
        },
        accessibility: {
          tabNavigation: `${firstFocused} → ${secondFocused}`
        },
        validation: validationMessages?.length || 0,
        consoleMessages,
        networkErrors
      }
    };
    
    fs.writeFileSync('login-qa-report.json', JSON.stringify(report, null, 2));
    console.log('\n✓ Detailed report saved as login-qa-report.json');
    
  } catch (error) {
    console.error('Test failed:', error);
    await page.screenshot({ path: 'test-error.png', fullPage: true });
  } finally {
    await context.close();
    await browser.close();
  }
}

testLoginPage().catch(console.error);