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

test.describe('H2H Application', () => {
  test('should load the homepage', async ({ page }) => {
    // Listen for page errors only (ignore 401 for public API)
    const pageErrors: Error[] = [];
    page.on('pageerror', error => {
      pageErrors.push(error);
    });

    await page.goto('/');

    // Wait for the page to load
    await page.waitForLoadState('networkidle');

    if (pageErrors.length > 0) {
      console.log('Page Errors:', pageErrors.map(e => e.message));
    }

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

    // Basic assertions
    await expect(page).toHaveTitle(/H2H/);
    // Should show the header with H2H logo
    await expect(page.locator('h1:has-text("H2H")')).toBeVisible();
  });

  test('should navigate to login page', async ({ page }) => {
    await page.goto('/');
    await page.waitForLoadState('networkidle');

    // Look for login button in header (first one)
    const loginButton = page.getByRole('link', { name: /log in/i }).first();
    await loginButton.click();

    await page.waitForLoadState('networkidle');

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

    await expect(page).toHaveURL(/login/);
  });

  test('should login as admin and see events on home page', async ({ page }) => {
    const pageErrors: Error[] = [];
    page.on('pageerror', error => {
      pageErrors.push(error);
    });

    // Go to login page
    await page.goto('/login');
    await page.waitForLoadState('networkidle');

    // Fill in login form
    await page.fill('input[type="email"]', 'admin@h2h.com');
    await page.fill('input[type="password"]', 'admin123');

    // Submit form
    await page.click('button[type="submit"]');

    // Wait for navigation after login - now redirects to home page with events
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(1000);

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

    // Home page should now show events heading
    await expect(page.getByRole('heading', { name: 'Upcoming Events' })).toBeVisible({ timeout: 5000 });

    if (pageErrors.length > 0) {
      console.log('Page Errors during flow:', pageErrors.map(e => e.message));
    }

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

  test('should complete full spread betting flow', async ({ page }) => {
    const pageErrors: Error[] = [];
    page.on('pageerror', error => {
      pageErrors.push(error);
    });

    // Login as alice
    await page.goto('/login');
    await page.waitForLoadState('networkidle');

    await page.fill('input[type="email"]', 'alice@example.com');
    await page.fill('input[type="password"]', 'password123');
    await page.click('button[type="submit"]');

    // Wait for home page to load with events
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(1000);

    // Events are now shown on the home page
    await expect(page.getByRole('heading', { name: 'Upcoming Events' })).toBeVisible({ timeout: 5000 });

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

    // Click on first event in the table
    const firstEventRow = page.locator('.divide-y button').first();
    if (await firstEventRow.isVisible()) {
      await firstEventRow.click();
      await page.waitForLoadState('networkidle');

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

      // Check if spread grid is visible
      const spreadButtons = page.locator('button').filter({ hasText: /^[+-]?\d+\.?\d*$/ });
      const count = await spreadButtons.count();
      console.log(`Found ${count} spread buttons`);

      // Try to create a bet by clicking an empty spread
      if (count > 0) {
        await spreadButtons.first().click({ timeout: 5000 }).catch(() => {
          console.log('Could not click spread button - might be occupied');
        });

        await page.waitForTimeout(1000);
        await page.screenshot({ path: 'tests/screenshots/create-bet-modal.png', fullPage: true });
      }
    }

    if (pageErrors.length > 0) {
      console.log('Page Errors during spread betting flow:', pageErrors.map(e => e.message));
    }

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