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

test('Debug application errors', async ({ page }) => {
  // Collect all console messages
  const consoleMessages: Array<{ type: string; text: string }> = [];
  page.on('console', msg => {
    consoleMessages.push({
      type: msg.type(),
      text: msg.text()
    });
  });

  // Collect page errors
  const pageErrors: Error[] = [];
  page.on('pageerror', error => {
    pageErrors.push(error);
  });

  // Collect network errors
  const networkErrors: Array<{ url: string; status: number }> = [];
  page.on('response', response => {
    if (response.status() >= 400) {
      networkErrors.push({
        url: response.url(),
        status: response.status()
      });
    }
  });

  console.log('\n=== Loading Homepage ===');
  await page.goto('/');

  // Wait a bit for any errors to show up
  await page.waitForTimeout(3000);

  // Take screenshot
  await page.screenshot({ path: 'tests/screenshots/debug-homepage.png', fullPage: true });

  // Print all collected information
  console.log('\n=== Console Messages ===');
  consoleMessages.forEach(msg => {
    console.log(`[${msg.type.toUpperCase()}] ${msg.text}`);
  });

  console.log('\n=== Page Errors ===');
  if (pageErrors.length > 0) {
    pageErrors.forEach(error => {
      console.log(`ERROR: ${error.message}`);
      console.log(`Stack: ${error.stack}`);
    });
  } else {
    console.log('No page errors!');
  }

  console.log('\n=== Network Errors ===');
  if (networkErrors.length > 0) {
    networkErrors.forEach(error => {
      console.log(`${error.status} - ${error.url}`);
    });
  } else {
    console.log('No network errors!');
  }

  // Check if the page has rendered properly
  console.log('\n=== Page Content Check ===');
  const bodyText = await page.textContent('body');
  console.log(`Page has content: ${bodyText ? 'YES' : 'NO'}`);
  console.log(`Body text length: ${bodyText?.length || 0} characters`);

  // Try to find the H2H title
  const h2hTitle = await page.locator('h1:has-text("H2H")').count();
  console.log(`Found H2H title: ${h2hTitle > 0 ? 'YES' : 'NO'}`);

  // Check for error messages in the page
  const errorText = bodyText?.toLowerCase() || '';
  if (errorText.includes('error') || errorText.includes('failed')) {
    console.log(`\nWARNING: Page contains error text!`);
    console.log('First 500 chars of body:', bodyText?.substring(0, 500));
  }

  // Verify no critical errors
  const criticalErrors = pageErrors.filter(e =>
    !e.message.includes('Warning') &&
    !e.message.includes('DevTools')
  );

  expect(criticalErrors.length).toBe(0);
});
