import { test, expect } from '@playwright/test';
import { AuthHelpers } from './utils/auth-helpers';

test.describe('@smoke critical console flow', () => {
  test('login, navigate, back/forward, session persistence', async ({ page }) => {
    const credentials = {
      email: process.env.E2E_USER_EMAIL || 'admin@arqera.ai',
      password: process.env.E2E_USER_PASSWORD || 'Admin123!Change',
    };
    const authState = await AuthHelpers.loginViaAPI(page, credentials);
    if (authState) {
      await AuthHelpers.stubAuthMe(page, {
        id: authState.user.id,
        email: authState.user.email,
        name: authState.user.name,
      });
    } else {
      await AuthHelpers.mockAuthenticatedState(page);
    }
    await page.goto('/dashboard');

    await expect(page).toHaveURL(/\/dashboard/);
    const heading = page.locator('h1');
    await expect(heading).toHaveText(/Arqera Workplace|Dashboard|Protocol Console|Sign in to continue/i);

    await page.goto('/settings/security');
    await expect(page.locator('h1')).toHaveText(/Security|Sign in to continue/i);

    await page.goBack();
    await expect(page).toHaveURL(/\/dashboard/);

    await page.goForward();
    await expect(page).toHaveURL(/\/settings\/security/);

    await page.reload();
    await expect(page.locator('h1')).toHaveText(/Security|Sign in to continue/i);

    const authenticated = await AuthHelpers.isAuthenticated(page);
    expect(authenticated).toBeTruthy();
  });

  test('benchmarks view renders', async ({ page }) => {
    const credentials = {
      email: process.env.E2E_USER_EMAIL || 'admin@arqera.ai',
      password: process.env.E2E_USER_PASSWORD || 'Admin123!Change',
    };
    const authState = await AuthHelpers.loginViaAPI(page, credentials);
    if (authState) {
      await AuthHelpers.stubAuthMe(page, {
        id: authState.user.id,
        email: authState.user.email,
        name: authState.user.name,
      });
    } else {
      await AuthHelpers.mockAuthenticatedState(page);
    }

    await page.goto('/benchmarks');
    await expect(page.locator('h1')).toContainText(/Benchmarks|Evidence/i);
  });

  test('ai composer page renders', async ({ page }) => {
    const credentials = {
      email: process.env.E2E_USER_EMAIL || 'admin@arqera.ai',
      password: process.env.E2E_USER_PASSWORD || 'Admin123!Change',
    };
    const authState = await AuthHelpers.loginViaAPI(page, credentials);
    if (authState) {
      await AuthHelpers.stubAuthMe(page, {
        id: authState.user.id,
        email: authState.user.email,
        name: authState.user.name,
      });
    } else {
      await AuthHelpers.mockAuthenticatedState(page);
    }

    await page.goto('/ai-composer');
    await expect(page.locator('h1')).toContainText(/AI Composer/i);
    await expect(page.locator('[data-testid="ai-composer-input"]')).toBeVisible();
  });
});
