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

const TEST_USER = {
  email: "admin@example.com",
  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");
}

async function hasProjects(page: import("@playwright/test").Page): Promise<boolean> {
  const dashboardPage = new DashboardPage(page);
  await dashboardPage.waitForDashboardLoad();

  const emptyMsg = page.getByText("开始优化您的AI可见性");
  const errorTitle = page.getByText("数据加载失败");
  const isEmpty = await emptyMsg.isVisible().catch(() => false);
  const isError = await errorTitle.isVisible().catch(() => false);
  return !isEmpty && !isError;
}

describe("健康状态Dashboard - 页面渲染测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("Dashboard页面标题正确显示为品牌健康中心", async ({ page }) => {
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.pageTitle).toBeVisible();
    await expect(dashboardPage.pageTitle).toHaveText("品牌健康中心");
  });

  test("页面副标题正确显示", async ({ page }) => {
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForDashboardLoad();

    if (!(await hasProjects(page))) {
      const emptySubtitle = page.getByText("GEO和SEO是AI营销时代的共生体");
      await expect(emptySubtitle).toBeVisible();
      return;
    }

    const projectSubtitle = page.getByText(/—/);
    await expect(projectSubtitle).toBeVisible();
  });
});

describe("健康状态Dashboard - 空状态测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("空状态时显示引导文案和创建项目按钮", async ({ page }) => {
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForDashboardLoad();

    const emptyMsg = page.getByText("开始优化您的AI可见性");
    const hasEmpty = await emptyMsg.isVisible().catch(() => false);
    if (!hasEmpty) { test.skip(); return; }

    await expect(emptyMsg).toBeVisible();
    const createBtn = page.getByRole("button", { name: /创建项目/ });
    await expect(createBtn.first()).toBeVisible();
  });
});

describe("健康状态Dashboard - KPI卡片测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("4个MetricCard全部显示", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    await expect(dashboardPage.activeProjectCard).toBeVisible();
    await expect(dashboardPage.contentOutputCard).toBeVisible();
    await expect(dashboardPage.aiCitationCard).toBeVisible();
    await expect(dashboardPage.completedProjectCard).toBeVisible();
  });

  test("活跃项目数卡片显示数值", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    await expect(dashboardPage.activeProjectCard).toBeVisible();
  });

  test("内容产出统计卡片显示数值", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    await expect(dashboardPage.contentOutputCard).toBeVisible();
  });

  test("AI引用率卡片显示百分比", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    await expect(dashboardPage.aiCitationCard).toBeVisible();
  });

  test("已完成项目卡片显示数值", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    await expect(dashboardPage.completedProjectCard).toBeVisible();
  });
});

describe("健康状态Dashboard - 生命周期进度测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("生命周期进度区域标题正确显示", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.lifecycleProgress).toBeVisible();
  });

  test("生命周期进度显示当前阶段Badge", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.lifecycleProgress).toBeVisible();
    const stageBadge = page.getByText(/当前阶段：/);
    await expect(stageBadge).toBeVisible();
  });

  test("生命周期进度条显示5个阶段", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.lifecycleProgress).toBeVisible();
    const stageLabels = page.getByText(/诊断分析|策略制定|内容生产|分发执行|监测优化/);
    const count = await stageLabels.count();
    expect(count).toBeGreaterThanOrEqual(5);
  });
});

describe("健康状态Dashboard - 推荐下一步测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("推荐下一步区域标题正确显示", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.recommendedNextStep).toBeVisible();
  });

  test("推荐下一步包含执行按钮", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.recommendedNextStep).toBeVisible();
    const executeBtn = page.getByRole("button", { name: /执行/ });
    await expect(executeBtn.first()).toBeVisible();
  });

  test("推荐下一步包含管理Agent和项目详情按钮", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.recommendedNextStep).toBeVisible();
    const agentBtn = page.getByRole("button", { name: /管理Agent/ });
    const detailBtn = page.getByRole("button", { name: /项目详情/ });
    await expect(agentBtn).toBeVisible();
    await expect(detailBtn).toBeVisible();
  });

  test("点击执行按钮跳转", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.recommendedNextStep).toBeVisible();
    const executeBtn = page.getByRole("button", { name: /执行/ }).first();
    if (await executeBtn.isVisible()) {
      await executeBtn.click();
    }
  });
});

describe("健康状态Dashboard - Agent活动测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("Agent活动卡片显示功能开发中", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.agentActivity).toBeVisible();
    await expect(page.getByText("功能开发中")).toBeVisible();
  });
});

describe("健康状态Dashboard - 骨架屏测试", () => {
  test("加载时显示骨架屏", async ({ page }) => {
    await loginAndWait(page);
  });
});

describe("健康状态Dashboard - 颜色传达状态测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("页面元素正确渲染", async ({ page }) => {
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForDashboardLoad();
    await expect(dashboardPage.pageTitle).toBeVisible();
  });

  test("MetricCard包含趋势标签", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForHealthCards();
    const trendLabels = page.getByText(/全部内容|平均引用率|共.*个项目|活跃.*个/);
    const count = await trendLabels.count();
    expect(count).toBeGreaterThan(0);
  });

  test("生命周期进度使用颜色区分阶段状态", async ({ page }) => {
    if (!(await hasProjects(page))) { test.skip(); return; }
    const dashboardPage = new DashboardPage(page);
    await expect(dashboardPage.lifecycleProgress).toBeVisible();
  });
});

describe("健康状态Dashboard - 响应式设计测试", () => {
  test.beforeEach(async ({ page }) => {
    await loginAndWait(page);
  });

  test("移动端视口下页面正常显示", async ({ page }) => {
    await page.setViewportSize({ width: 375, height: 667 });
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForDashboardLoad();
    await expect(dashboardPage.pageTitle).toBeVisible();
  });

  test("桌面端视口下KPI卡片可见", async ({ page }) => {
    await page.setViewportSize({ width: 1280, height: 720 });
    const dashboardPage = new DashboardPage(page);
    await dashboardPage.waitForDashboardLoad();
    await expect(dashboardPage.pageTitle).toBeVisible();
    if (await hasProjects(page)) {
      await expect(dashboardPage.activeProjectCard).toBeVisible();
      await expect(dashboardPage.contentOutputCard).toBeVisible();
      await expect(dashboardPage.aiCitationCard).toBeVisible();
      await expect(dashboardPage.completedProjectCard).toBeVisible();
    }
  });
});
