import { test, expect } from "@playwright/test";
import { LoginPage } from "../pages/login.page";
import { DashboardPage } from "../pages/dashboard.page";

const TEST_USER = {
  email: process.env.E2E_TEST_EMAIL || "admin@example.com",
  password: process.env.E2E_TEST_PASSWORD || "admin@123",
};

async function loginAndWait(page: import("@playwright/test").Page) {
  const loginPage = new LoginPage(page);
  await loginPage.goto();
  await loginPage.login(TEST_USER.email, TEST_USER.password);
  try {
    await page.waitForURL(/\/dashboard/, { timeout: 60000 });
  } catch {
    const currentUrl = page.url();
    if (!currentUrl.includes("/dashboard")) {
      await loginPage.goto();
      await loginPage.login(TEST_USER.email, TEST_USER.password);
      await page.waitForURL(/\/dashboard/, { timeout: 60000 });
    }
  }
  await page.waitForLoadState("networkidle");
}

test.describe("核心流程烟雾测试", () => {
  test("登录→创建品牌→触发诊断→查看诊断结果", async ({ page }) => {
    const loginPage = new LoginPage(page);
    const dashboardPage = new DashboardPage(page);

    await loginPage.goto();
    await loginPage.login(TEST_USER.email, TEST_USER.password);

    await page.waitForURL(/\/(dashboard|onboarding)/, { timeout: 15000 });

    const currentUrl = page.url();
    if (currentUrl.includes("/onboarding")) {
      const brandInput = page.locator('input[placeholder*="品牌"]');
      if (await brandInput.isVisible()) {
        await brandInput.fill("测试品牌E2E");
        await page.getByRole("button", { name: /检测/ }).click();
        await expect(page.locator("text=核心维度评分")).toBeVisible({ timeout: 30000 }).catch(() => {});
        const nextButton = page.getByRole("button", { name: /注册|下一步/ }).first();
        if (await nextButton.isVisible()) {
          await nextButton.click();
        }
      }
    }

    await page.goto("/dashboard");
    await page.waitForLoadState("domcontentloaded");

    await expect(page.locator("body")).toBeVisible();
  });

  test("Dashboard页面加载并显示关键元素", async ({ page }) => {
    await loginAndWait(page);

    const dashboardPage = new DashboardPage(page);
    await dashboardPage.goto();

    await expect(page.locator("body")).toBeVisible();

    await expect(page.locator("nav")).toBeVisible();
  });
});
