/**
 * E2E tests for Bitable views — the standalone /bitable route hierarchy.
 *
 * Navigation: login via UI form → click TopNav "多维表格" icon (SPA navigate
 * to /bitable). This avoids the whoami cold-start bug that page.goto would
 * trigger on a full reload.
 *
 * ponytail: bitable backend may not be fully configured (no DATABASE_URL);
 * the view should still render its topbar and file list gracefully.
 */

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

async function loginAndOpenBitable(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 /bitable via the TopNav "多维表格" button.
  await page.getByRole('button', { name: '多维表格' }).click()
  await expect(page).toHaveURL(/\/bitable/, { timeout: 15_000 })
  await expect(page.locator('.bitable-file-list-view')).toBeVisible({ timeout: 15_000 })
}

test.describe('Bitable View E2E', () => {
  test.beforeAll(async () => {
    try {
      await waitForServer(undefined, 5_000)
    } catch {
      test.skip(true, 'Backend not running — skipping bitable view E2E')
    }
  })

  test('B1: bitable file list loads without white screen or 401 redirect', async ({ page }) => {
    await loginAndOpenBitable(page)

    // URL should be /bitable, not redirected to /login.
    await expect(page).toHaveURL(/\/bitable/, { timeout: 10_000 })
    // File list view root element visible — no white screen.
    await expect(page.locator('.bitable-file-list-view')).toBeVisible()
  })

  test('B2: bitable file list core elements are visible', async ({ page }) => {
    await loginAndOpenBitable(page)

    // The topbar title "多维表格" should be visible.
    await expect(page.locator('.bitable-file-list-view__title')).toContainText('多维表格', {
      timeout: 15_000,
    })

    // Either the file grid (cards) or the empty state is rendered.
    await expect
      .poll(
        async () => {
          const grid = await page.locator('.bitable-file-list-view__grid').count()
          const empty = await page.locator('.bitable-file-list-view__empty').count()
          return grid + empty
        },
        { timeout: 15_000, intervals: [1_000] },
      )
      .toBeGreaterThan(0)
  })

  test('B3: new file button is visible and clickable', async ({ page }) => {
    await loginAndOpenBitable(page)

    const newButton = page.getByRole('button', { name: /新建文件/ })
    await expect(newButton).toBeVisible({ timeout: 10_000 })
  })
})
