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

test.describe('End-to-End Spread Betting Flow', () => {
  test('should allow admin to create event and user to place bet', async ({ page, context }) => {
    // Track errors
    const pageErrors: string[] = [];
    page.on('pageerror', error => {
      pageErrors.push(error.message);
    });

    console.log('\n=== Step 1: Login as Admin ===');
    await page.goto('/login');
    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);
    await page.screenshot({ path: 'tests/screenshots/e2e-01-admin-login.png', fullPage: true });
    console.log('✓ Admin logged in successfully');

    console.log('\n=== Step 2: Navigate to Admin Panel ===');
    const adminLink = page.getByRole('link', { name: /admin/i });
    if (await adminLink.isVisible()) {
      await adminLink.click();
      await page.waitForLoadState('networkidle');
      await page.screenshot({ path: 'tests/screenshots/e2e-02-admin-panel.png', fullPage: true });
      console.log('✓ Admin panel loaded');
    } else {
      console.log('! Admin link not visible - user might not have admin privileges');
    }

    console.log('\n=== Step 3: View Sport Events on Home Page ===');
    await page.goto('/');
    await page.waitForLoadState('networkidle');
    await page.screenshot({ path: 'tests/screenshots/e2e-03-sport-events.png', fullPage: true });
    console.log('✓ Sport events page loaded');

    // Count available events in the table
    const eventRows = page.locator('.divide-y button');
    const eventCount = await eventRows.count();
    console.log(`✓ Found ${eventCount} sport events`);

    if (eventCount > 0) {
      console.log('\n=== Step 4: View Event Spread Grid ===');
      await eventRows.first().click();
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(1000);
      await page.screenshot({ path: 'tests/screenshots/e2e-04-spread-grid.png', fullPage: true });
      console.log('✓ Spread grid displayed');

      // Check for spread grid
      const gridExists = await page.locator('.grid').count() > 0;
      console.log(`Grid container found: ${gridExists}`);

      // Log page content for debugging
      const pageContent = await page.textContent('body');
      if (pageContent?.includes('Wake Forest') || pageContent?.includes('Lakers') || pageContent?.includes('Chiefs')) {
        console.log('✓ Event details are visible on page');
      }
    }

    console.log('\n=== Step 5: Logout and Login as Regular User ===');
    await page.goto('/');
    await page.waitForLoadState('networkidle');
    await page.getByRole('button', { name: /logout/i }).click();
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(1000);
    await page.screenshot({ path: 'tests/screenshots/e2e-05-logged-out.png', fullPage: true });
    console.log('✓ Logged out successfully');

    // Login as Alice
    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);
    await page.screenshot({ path: 'tests/screenshots/e2e-06-alice-login.png', fullPage: true });
    console.log('✓ Alice logged in successfully');

    console.log('\n=== Step 6: Alice Views Sport Events on Home ===');
    // Events are now on the home page
    await expect(page.getByRole('heading', { name: 'Upcoming Events' })).toBeVisible({ timeout: 5000 });
    await page.screenshot({ path: 'tests/screenshots/e2e-07-alice-events.png', fullPage: true });
    console.log('✓ Alice can view sport events');

    console.log('\n=== Error Summary ===');
    if (pageErrors.length > 0) {
      console.log('Page Errors:', pageErrors);
    } else {
      console.log('✓ No page errors!');
    }

    // Verify no critical errors
    expect(pageErrors.length).toBe(0);
  });
});
