import { Page, Locator, expect } from "@playwright/test";

export class DashboardPage {
  readonly page: Page;
  readonly pageTitle: Locator;
  readonly activeProjectCard: Locator;
  readonly contentOutputCard: Locator;
  readonly aiCitationCard: Locator;
  readonly completedProjectCard: Locator;
  readonly lifecycleProgress: Locator;
  readonly recommendedNextStep: Locator;
  readonly agentActivity: Locator;
  readonly emptyStateMessage: Locator;
  readonly createProjectButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.pageTitle = page.getByRole("heading", { name: "品牌健康中心" });
    this.activeProjectCard = page.locator("text=活跃项目数").first();
    this.contentOutputCard = page.locator("text=内容产出统计").first();
    this.aiCitationCard = page.locator("text=AI引用率").first();
    this.completedProjectCard = page.locator("text=已完成项目").first();
    this.lifecycleProgress = page.locator("text=生命周期进度").first();
    this.recommendedNextStep = page.locator("text=推荐下一步").first();
    this.agentActivity = page.locator("text=Agent活动").first();
    this.emptyStateMessage = page.locator("text=开始优化您的AI可见性").first();
    this.createProjectButton = page.getByRole("button", { name: /创建项目/ }).first();
  }

  async goto() {
    await this.page.goto("/dashboard");
  }

  async expectToBeVisible() {
    await expect(this.pageTitle).toBeVisible();
  }

  async waitForDashboardLoad() {
    await expect(this.pageTitle).toBeVisible({ timeout: 15000 });
  }

  async waitForEmptyState() {
    await expect(this.emptyStateMessage).toBeVisible({ timeout: 15000 });
  }

  async waitForHealthCards() {
    await expect(this.activeProjectCard).toBeVisible({ timeout: 15000 });
  }

  async getMetricCardValue(label: string): Promise<string | null> {
    const card = this.page.locator(`text=${label}`).first();
    if (await card.isVisible()) {
      const parent = card.locator("..");
      const valueEl = parent.locator(".text-2xl, .text-3xl").first();
      if (await valueEl.isVisible()) {
        return valueEl.textContent();
      }
    }
    return null;
  }

  async getStageProgressCount(): Promise<number> {
    const stages = this.page.locator("[data-stage-status]");
    return stages.count();
  }

  async getRecommendationTitle(): Promise<string | null> {
    const title = this.page.locator(".text-sm.font-semibold.text-gray-900").first();
    if (await title.isVisible()) {
      return title.textContent();
    }
    return null;
  }
}
