import { chromium } from "playwright";

const baseURL = process.env.PROTOTYPE_URL || "http://127.0.0.1:5174/";
const browser = await chromium.launch({
  headless: true,
  executablePath:
    process.env.BROWSER_PATH ||
    "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
});
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const checks = [];
const check = async (name, run) => {
  await run();
  checks.push({ name, pass: true });
};

try {
  await page.goto(`${baseURL}?authGate=1`, { waitUntil: "networkidle" });
  await page.evaluate(() => {
    localStorage.removeItem("running-ai-access-token");
    localStorage.removeItem("running-ai-prd-v1");
  });
  await page.reload({ waitUntil: "networkidle" });

  await check("游客首屏明确展示演示数据", async () => {
    await page.getByText("游客预览", { exact: true }).waitFor();
    await page.getByText("当前展示演示数据，不会写入云端").waitFor();
  });

  await check("游客可浏览全部一级入口且不会被登录拦截", async () => {
    for (const label of ["训练", "营养", "我的", "首页"]) {
      await page.getByRole("button", { name: label, exact: true }).click();
      if (await page.locator(".auth-page--embedded").count()) {
        throw new Error(`${label} 一级入口被错误要求登录`);
      }
    }
  });

  await check("PROFILE-01 登录弹层锁定底层滚动与一级导航", async () => {
    await page.getByRole("button", { name: "我的", exact: true }).click();
    await page.getByRole("button", { name: "进入账号与安全" }).click();
    await page.getByRole("dialog", { name: "登录后管理个人账号" }).waitFor();

    const content = page.locator(".screen-content");
    const navLock = page.locator(".bottom-nav-lock");
    if ((await content.getAttribute("inert")) === null)
      throw new Error("登录弹层打开后页面内容未设为 inert");
    if ((await navLock.getAttribute("inert")) === null)
      throw new Error("登录弹层打开后一级导航未设为 inert");

    const beforeScroll = await content.evaluate((node) => node.scrollTop);
    const overlayBox = await page.locator(".phone-modal-layer").boundingBox();
    if (!overlayBox) throw new Error("登录弹层没有独立顶层容器");
    await page.mouse.move(
      overlayBox.x + overlayBox.width / 2,
      overlayBox.y + overlayBox.height / 2,
    );
    await page.mouse.wheel(0, 600);
    await page.waitForTimeout(120);
    const afterScroll = await content.evaluate((node) => node.scrollTop);
    if (afterScroll !== beforeScroll)
      throw new Error(`登录弹层发生滚动穿透：${beforeScroll} -> ${afterScroll}`);

    const trainingNavBox = await page
      .locator(".bottom-nav button")
      .filter({ hasText: "训练" })
      .boundingBox();
    if (!trainingNavBox) throw new Error("找不到训练一级入口");
    await page.mouse.click(
      trainingNavBox.x + trainingNavBox.width / 2,
      trainingNavBox.y + trainingNavBox.height / 2,
    );
    await page.waitForTimeout(120);
    await page.locator(".stage-note b").filter({ hasText: "PROFILE-01" }).waitFor();

    await page.getByRole("button", { name: "暂不登录，继续预览" }).click();
    if ((await content.getAttribute("inert")) !== null)
      throw new Error("关闭登录弹层后页面内容仍处于 inert");
    await page.waitForTimeout(40);
    const restoredLabel = await page.evaluate(() =>
      document.activeElement?.getAttribute("aria-label"),
    );
    if (restoredLabel !== "进入账号与安全")
      throw new Error(`关闭登录弹层后焦点未恢复：${restoredLabel ?? "无焦点"}`);
    await page.getByRole("button", { name: "训练", exact: true }).click();
    await page.locator(".stage-note b").filter({ hasText: "TRAIN-HUB" }).waitFor();
  });

  await check("游客可进入设备页但连接动作触发统一登录说明", async () => {
    await page.locator(".demo-list button").nth(3).click();
    await page.getByRole("button", { name: "连接我的设备" }).click();
    await page
      .locator(".provider-row")
      .filter({ hasText: "Apple Health" })
      .getByRole("button", { name: "连接" })
      .click();
    await page.getByRole("dialog", { name: "登录后连接运动设备" }).waitFor();
    await page.getByText("当前展示的是本地演示数据", { exact: false }).count();
    await page.getByRole("button", { name: "暂不登录，继续预览" }).click();
    await page.getByText("让建议基于真实数据").waitFor();
  });

  await check("登录后保留当前页面并自动继续原受限动作", async () => {
    const connect = page
      .locator(".provider-row")
      .filter({ hasText: "Apple Health" })
      .getByRole("button", { name: "连接" });
    await connect.click();
    await page.locator(".auth-page--embedded .check-row input").check();
    await page
      .locator(".auth-page--embedded")
      .getByRole("button", { name: "微信一键登录" })
      .click();
    await page.getByRole("button", { name: "授权并登录" }).click();
    await page.getByText("个人模式", { exact: true }).waitFor({ timeout: 5000 });
    await page.getByText(/Apple Health 已连接/).waitFor({ timeout: 5000 });
    const token = await page.evaluate(() =>
      localStorage.getItem("running-ai-access-token"),
    );
    if (!token) throw new Error("登录成功后未保存会话令牌");
  });

  await check("登录态不再显示受限能力角标", async () => {
    const visibleBadges = await page.locator("[data-auth-required]").evaluateAll((nodes) =>
      nodes.filter((node) => getComputedStyle(node, "::after").display !== "none").length,
    );
    if (visibleBadges) throw new Error(`登录后仍显示 ${visibleBadges} 个登录后可用角标`);
  });

  console.log(JSON.stringify({ ok: true, checks }, null, 2));
} catch (error) {
  console.error(JSON.stringify({ ok: false, checks, error: String(error) }, null, 2));
  process.exitCode = 1;
} finally {
  await browser.close();
}
