import { resolve } from "node:path";

import { expect, test } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";

let vite: ViteDevServer;
let webUrl: string;

test.beforeAll(async () => {
  vite = await createServer({
    configFile: resolve("apps/web/vite.config.ts"),
    root: resolve("apps/web"),
    server: { host: "127.0.0.1", port: 0 },
  });
  await vite.listen();
  const address = vite.httpServer?.address();
  if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
  webUrl = `http://127.0.0.1:${address.port}`;
});

test.afterAll(async () => vite.close());

test("TDD-WP1-AUTH-003 keeps registration and login as separate keyboard entries", async ({ page }) => {
  await page.goto(webUrl);
  const loginTab = page.getByRole("tab", { name: "登录" });
  const registerTab = page.getByRole("tab", { name: "注册" });

  await expect(loginTab).toHaveAttribute("aria-selected", "true");
  await expect(page.getByRole("textbox", { name: "邀请码" })).toHaveCount(0);
  await loginTab.focus();
  await page.keyboard.press("ArrowRight");
  await expect(registerTab).toBeFocused();
  await expect(registerTab).toHaveAttribute("aria-selected", "true");
  await expect(page.getByRole("textbox", { name: "邀请码" })).toBeVisible();
  await page.keyboard.press("ArrowLeft");
  await expect(loginTab).toBeFocused();
  await expect(page.getByRole("textbox", { name: "邀请码" })).toHaveCount(0);
  await expect(page.getByRole("link", { name: "管理员登录" })).toHaveAttribute("href", "/admin/login");
  await expect(page.getByText("测试数据仅保存在本机，不自动备份，也不会迁移到正式系统。")).toBeVisible();
});
