/**
 * E2E tests for SkillsView — 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.
 *
 * ponytail: page.goto('/agent/monitor') would trigger the whoami cold-start
 * bug (refresh token passed as RequestInit property). SPA navigation via
 * TopNav button preserves the in-memory access token.
 */

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

async function loginAndOpenSkillsTab(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()
  await expect(page.locator('.skills-view')).toBeVisible({ timeout: 15_000 })
}

test.describe('Skills View E2E', () => {
  test('S1: skills tab loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenSkillsTab(page)

    // URL should stay on /agent (workbench), not redirect to /login.
    await expect(page).toHaveURL(/\/agent/, { timeout: 10_000 })
    // SkillsView root element visible — no white screen.
    await expect(page.locator('.skills-view')).toBeVisible()
  })

  test('S2: skills core elements are visible', async ({ page }) => {
    await loginAndOpenSkillsTab(page)

    // The "安装技能" button is always present in the header.
    await expect(page.getByRole('button', { name: /安装技能/ })).toBeVisible({
      timeout: 15_000,
    })

    // Either skill cards exist or the empty state "暂无已注册技能" is shown.
    await expect
      .poll(
        async () => {
          const cards = await page.locator('.skill-card').count()
          const empty = await page
            .locator('.ant-empty', { hasText: '暂无已注册技能' })
            .count()
          return cards + empty
        },
        { timeout: 20_000, intervals: [1_000] },
      )
      .toBeGreaterThan(0)
  })
})
