/**
 * E2E tests for SettingsView — 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 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 loginAndOpenSettingsTab(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('.settings-view')).toBeVisible({ timeout: 15_000 })
}

test.describe('Settings View E2E', () => {
  test('T1: settings tab loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenSettingsTab(page)

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

  test('T2: settings form core elements are visible', async ({ page }) => {
    await loginAndOpenSettingsTab(page)

    // The settings tabs container should be visible.
    await expect(page.locator('.settings-tabs')).toBeVisible({ timeout: 15_000 })
    // The "LLM 配置" tab should be present (default active tab).
    await expect(
      page.locator('.ant-tabs-tab', { hasText: 'LLM 配置' }),
    ).toBeVisible({ timeout: 15_000 })
  })
})
