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

test('Rewards page loads without errors', async ({ page }) => {
  const errors: string[] = [];

  // Capture console errors
  page.on('console', msg => {
    if (msg.type() === 'error') {
      errors.push(msg.text());
    }
  });

  // Capture page errors
  page.on('pageerror', err => {
    errors.push(err.message);
  });

  // Navigate to rewards page
  await page.goto('/rewards', { waitUntil: 'domcontentloaded' });

  // Wait for page content
  await page.waitForTimeout(2000);

  // Check for the Rewards heading
  const heading = page.locator('h1:has-text("Rewards")');
  await expect(heading).toBeVisible({ timeout: 5000 });
  console.log('✓ Rewards page heading found');

  // Check for key sections - use first() since there are multiple matches
  const leaderboardSection = page.locator('h3:has-text("Leaderboard")').first();
  const activitySection = page.locator('h3:has-text("Activity")').first();

  // At least one of these should be visible
  const hasContent = await leaderboardSection.isVisible() || await activitySection.isVisible();
  expect(hasContent).toBe(true);
  console.log('✓ Gamification content sections found');

  // Report any errors
  if (errors.length > 0) {
    console.log('Console errors found:', errors);
  }

  // Filter out API errors (expected when backend isn't running)
  const criticalErrors = errors.filter(e =>
    !e.includes('Failed to load resource') &&
    !e.includes('ERR_CONNECTION_REFUSED')
  );

  expect(criticalErrors.length).toBe(0);
  console.log('✓ No critical errors on Rewards page');
});

test('Home page loads (may show loading if backend unavailable)', async ({ page }) => {
  await page.goto('/', { waitUntil: 'domcontentloaded' });

  // Wait for content
  await page.waitForTimeout(2000);

  // Check for H2H branding in header
  await expect(page.locator('header h1:has-text("H2H")')).toBeVisible({ timeout: 5000 });
  console.log('✓ H2H header found');

  // Check navigation includes Rewards link (use first() since there may be multiple)
  await expect(page.locator('nav a[href="/rewards"]').first()).toBeVisible({ timeout: 5000 });
  console.log('✓ Rewards nav link found');

  // Page either shows loading state or full content - both are acceptable
  // when backend is not running
  const hasSpinner = await page.locator('.animate-spin').first().isVisible();
  const hasContent = await page.locator('text=Upcoming Events').isVisible();
  console.log(`✓ Home page rendered (loading: ${hasSpinner}, content: ${hasContent})`);
});
