/**
 * E2E tests for EvolutionView — the bottom-right "监控" quadrant tab.
 *
 * Navigation: login via UI form → click TopNav "setting" icon (SPA navigate
 * to /agent/monitor workbench layout) → click the "监控" quadrant tab.
 *
 * The "监控" tab is the default for the bottom-right QuadrantPanel, but we
 * click it explicitly to be deterministic.
 *
 * ponytail: page.goto would trigger the whoami cold-start bug; SPA
 * navigation via TopNav preserves the in-memory access token.
 */

import { test, expect, type Page } from '@playwright/test'
import { TEST_USER, clearAuth } from './helpers'

async function loginAndOpenMonitorTab(page: Page): Promise<void> {
  await page.goto('/login')
  await clearAuth(page)
  await page.getByPlaceholder('请输入用户名').fill(TEST_USER.username)
  await page.getByPlaceholder('请输入密码').fill(TEST_USER.password)
  await page.getByRole('button', { name: /登\s*录/ }).click()
  await expect(page).toHaveURL(/\/agent/, { timeout: 15_000 })

  // SPA-navigate to the workbench layout via the TopNav settings icon.
  await page.getByRole('button', { name: 'setting' }).click()
  await expect(page.locator('.quadrant-panel__tab').first()).toBeVisible({
    timeout: 15_000,
  })

  // Activate the "监控" tab in the bottom-right QuadrantPanel.
  await page.locator('.quadrant-panel__tab', { hasText: '监控' }).click()
  // /agent/monitor renders EvolutionView in both the router-view (left pane)
  // and the bottom-right quadrant's monitor slot — use .first() to avoid
  // strict mode violation.
  await expect(page.locator('.evolution-container').first()).toBeVisible({
    timeout: 15_000,
  })
}

test.describe('Evolution View E2E', () => {
  test('E1: evolution view loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenMonitorTab(page)

    // URL should stay on /agent (workbench), not redirect to /login.
    await expect(page).toHaveURL(/\/agent/, { timeout: 10_000 })
    // EvolutionView root element visible — no white screen.
    // .first() because /agent/monitor renders EvolutionView in two panes.
    await expect(page.locator('.evolution-container').first()).toBeVisible()
  })

  test('E2: evolution dashboard core elements are visible', async ({ page }) => {
    await loginAndOpenMonitorTab(page)

    // The evolution tabs container should be visible (.first(): two instances).
    await expect(page.locator('.evolution-tabs').first()).toBeVisible({
      timeout: 15_000,
    })
    // The "概览+指标" tab should be present.
    await expect(
      page.locator('.ant-tabs-tab', { hasText: '概览+指标' }).first(),
    ).toBeVisible({ timeout: 15_000 })
  })
})
