/**
 * E2E tests for KnowledgeBaseView — the top-right "知识库" quadrant tab.
 *
 * Navigation: login via UI form → click TopNav "setting" icon (SPA navigate
 * to /agent/monitor workbench layout) → click the "知识库" tab in the
 * top-right QuadrantPanel.
 *
 * 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 loginAndOpenKnowledgeTab(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 top-right QuadrantPanel.
  await page.locator('.quadrant-panel__tab', { hasText: '知识库' }).click()
  await expect(page.locator('.kb-view')).toBeVisible({ timeout: 15_000 })
}

test.describe('Knowledge Base View E2E', () => {
  test('K1: knowledge tab loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenKnowledgeTab(page)

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

  test('K2: knowledge base core elements are visible', async ({ page }) => {
    await loginAndOpenKnowledgeTab(page)

    // The a-tabs should render with the "文档管理" tab visible.
    await expect(
      page.locator('.ant-tabs-tab', { hasText: '文档管理' }),
    ).toBeVisible({ timeout: 15_000 })
  })
})
