/**
 * E2E tests for Admin DashboardView — the /admin/dashboard route.
 *
 * Navigation: login via UI form → click TopNav admin console icon (SPA
 * navigate to /admin/dashboard). The admin button is rendered only when
 * authStore.isAdmin() is true; the test user has the admin role.
 *
 * ponytail: page.goto('/admin/dashboard') would trigger the whoami
 * cold-start bug (refresh token passed as RequestInit property). 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 loginAndOpenAdmin(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 /admin/dashboard via the TopNav admin console button.
  // exact: true is needed because the chat input bar also has a button named
  // "team 私董会" which would match a substring search for "team".
  await page.getByRole('button', { name: 'team', exact: true }).click()
  await expect(page).toHaveURL(/\/admin\/dashboard/, { timeout: 15_000 })
  await expect(page.locator('.dashboard-view')).toBeVisible({ timeout: 15_000 })
}

test.describe('Admin Dashboard View E2E', () => {
  test('A1: admin dashboard loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenAdmin(page)

    // URL should be /admin/dashboard, not redirected to /login or /agent.
    await expect(page).toHaveURL(/\/admin\/dashboard/, { timeout: 10_000 })
    // DashboardView root element visible — no white screen.
    await expect(page.locator('.dashboard-view')).toBeVisible()
  })

  test('A2: admin dashboard core elements are visible', async ({ page }) => {
    await loginAndOpenAdmin(page)

    // The page header "管理概览" should be visible.
    await expect(page.locator('.dashboard-view__header')).toBeVisible({
      timeout: 15_000,
    })
    // At least one stat card should be rendered (departments/users/skills/kb).
    await expect(page.locator('.dashboard-view__stat-card').first()).toBeVisible({
      timeout: 15_000,
    })
  })
})
