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

test('Capture actual browser errors', async ({ page }) => {
  console.log('\n=== CAPTURING ALL BROWSER CONSOLE OUTPUT ===\n');

  const allMessages: any[] = [];

  page.on('console', msg => {
    const msgData = {
      type: msg.type(),
      text: msg.text(),
      location: msg.location()
    };
    allMessages.push(msgData);

    const prefix = msg.type() === 'error' ? '❌ ERROR' :
                   msg.type() === 'warning' ? '⚠️  WARNING' :
                   msg.type() === 'log' ? '📝 LOG' :
                   `ℹ️  ${msg.type().toUpperCase()}`;

    console.log(`${prefix}: ${msg.text()}`);
    if (msg.location().url) {
      console.log(`   Location: ${msg.location().url}:${msg.location().lineNumber}`);
    }
  });

  page.on('pageerror', error => {
    console.log(`\n💥 PAGE ERROR: ${error.message}`);
    console.log(`   Stack: ${error.stack}\n`);
  });

  page.on('requestfailed', request => {
    console.log(`\n🔴 REQUEST FAILED: ${request.url()}`);
    console.log(`   Failure: ${request.failure()?.errorText}\n`);
  });

  console.log('\nLoading: /\n');

  try {
    await page.goto('/', { waitUntil: 'networkidle', timeout: 30000 });
  } catch (e) {
    console.log(`\n❌ Failed to load page: ${e}\n`);
  }

  // Wait a bit more to capture any delayed errors
  await page.waitForTimeout(3000);

  console.log('\n=== SUMMARY ===');
  console.log(`Total console messages: ${allMessages.length}`);
  console.log(`Errors: ${allMessages.filter(m => m.type === 'error').length}`);
  console.log(`Warnings: ${allMessages.filter(m => m.type === 'warning').length}`);

  const errors = allMessages.filter(m => m.type === 'error');
  if (errors.length > 0) {
    console.log('\n=== ALL ERRORS ===');
    errors.forEach((err, i) => {
      console.log(`\n${i + 1}. ${err.text}`);
      if (err.location.url) {
        console.log(`   ${err.location.url}:${err.location.lineNumber}`);
      }
    });
  }

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