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

test('Complete application flow verification', async ({ page }) => {
  const errors: string[] = [];
  page.on('pageerror', error => errors.push(`PAGE ERROR: ${error.message}`));

  console.log('\n====================================');
  console.log('   TESTING H2H APPLICATION');
  console.log('====================================\n');

  // Test 1: Homepage loads
  console.log('TEST 1: Loading homepage...');
  await page.goto('/');
  await page.waitForLoadState('networkidle');
  const title = await page.title();
  console.log(`✓ Homepage loaded: "${title}"`);
  await page.screenshot({ path: 'tests/screenshots/flow-01-homepage.png' });

  // Test 2: Can navigate to login (button in header now)
  console.log('\nTEST 2: Navigating to login...');
  await page.getByRole('link', { name: /log in/i }).first().click();
  await page.waitForURL('**/login');
  console.log('✓ Login page loaded');
  await page.screenshot({ path: 'tests/screenshots/flow-02-login.png' });

  // Test 3: Can login as admin
  console.log('\nTEST 3: Logging in as admin...');
  await page.fill('input[type="email"]', 'admin@h2h.com');
  await page.fill('input[type="password"]', 'admin123');
  await page.click('button[type="submit"]');
  await page.waitForLoadState('networkidle');
  await page.waitForTimeout(1000);
  const currentUrl = page.url();
  console.log(`✓ Logged in successfully, redirected to: ${currentUrl}`);
  await page.screenshot({ path: 'tests/screenshots/flow-03-logged-in.png' });

  // Test 4: Check navigation links (events are now on home page)
  console.log('\nTEST 4: Checking available navigation links...');
  const links = await page.locator('nav a').allTextContents();
  console.log('Available links:', links);
  const hasAdmin = links.some(l => l.toLowerCase().includes('admin'));
  const hasMyBets = links.some(l => l.toLowerCase().includes('my bets'));
  const hasWallet = links.some(l => l.toLowerCase().includes('wallet'));
  console.log(`  - Admin link: ${hasAdmin ? '✓ Found' : '✗ Not found'}`);
  console.log(`  - My Bets link: ${hasMyBets ? '✓ Found' : '✗ Not found'}`);
  console.log(`  - Wallet link: ${hasWallet ? '✓ Found' : '✗ Not found'}`);

  // Test 5: Home page shows events for authenticated users
  console.log('\nTEST 5: Checking events on home page...');
  await expect(page.getByRole('heading', { name: 'Upcoming Events' })).toBeVisible({ timeout: 5000 });
  console.log('✓ Upcoming Events section visible');

  // Check for events in the table
  const eventRows = page.locator('.divide-y button');
  const eventCount = await eventRows.count();
  console.log(`✓ Found ${eventCount} sport events`);
  await page.screenshot({ path: 'tests/screenshots/flow-04-events-home.png' });

  if (eventCount > 0) {
    console.log('\nTEST 6: Viewing event spread grid...');
    await eventRows.first().click();
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(1000);
    console.log('✓ Event details loaded');
    await page.screenshot({ path: 'tests/screenshots/flow-05-spread-grid.png' });

    // Check if spread grid is visible
    const bodyText = await page.textContent('body');
    const hasEventName = bodyText?.includes('Wake Forest') || bodyText?.includes('Lakers') || bodyText?.includes('Chiefs');
    console.log(`  - Event details visible: ${hasEventName ? '✓ Yes' : '✗ No'}`);

    // Go back to home
    await page.click('button:has-text("Back to Events")');
    await page.waitForLoadState('networkidle');
  }

  // Test 7: Can login as regular user
  console.log('\nTEST 7: Testing regular user login...');
  await page.getByRole('button', { name: /logout/i }).click();
  await page.waitForTimeout(1000);
  await page.goto('/login');
  await page.fill('input[type="email"]', 'alice@example.com');
  await page.fill('input[type="password"]', 'password123');
  await page.click('button[type="submit"]');
  await page.waitForLoadState('networkidle');
  await page.waitForTimeout(1000);
  console.log('✓ Alice logged in successfully');
  await page.screenshot({ path: 'tests/screenshots/flow-06-alice-login.png' });

  // Check alice's navigation - should NOT have admin link
  const aliceLinks = await page.locator('nav a').allTextContents();
  const aliceHasAdmin = aliceLinks.some(l => l.toLowerCase().includes('admin'));
  console.log(`  - Admin link for Alice: ${aliceHasAdmin ? '✗ SHOULD NOT BE VISIBLE' : '✓ Correctly hidden'}`);

  console.log('\n====================================');
  console.log('   ERROR SUMMARY');
  console.log('====================================');
  if (errors.length > 0) {
    console.log('\nErrors found:');
    errors.forEach(e => console.log(`  ✗ ${e}`));
  } else {
    console.log('\n✓ NO ERRORS - Application is working correctly!');
  }
  console.log('\n====================================\n');

  // Final assertion
  expect(errors.length).toBe(0);
});
