import { test, expect } from "@playwright/test";
import { mockApi, 登录 } from "../测试夹具";

test.describe("离线：记账与恢复同步", () => {
  test("01-服务 API 不可用时显示底部离线横幅且不遮挡页面", async ({ page }) => {
    const state = await mockApi(page);
    await 登录(page);
    state.apiAvailable = false;
    await page.reload();
    await expect(page.getByRole("status", { name: "服务暂不可用，点击重连" })).toBeVisible();
    await expect(page.getByRole("navigation", { name: "主导航" })).toBeVisible();
    const banner = page.getByRole("status", { name: "服务暂不可用，点击重连" });
    const nav = page.getByRole("navigation", { name: "主导航" });
    expect((await banner.boundingBox())!.y).toBeLessThan((await nav.boundingBox())!.y);
  });

  test("02-离线时仍可立即新增账目并标记待同步", async ({ page }) => {
    const state = await mockApi(page);
    await 登录(page);
    state.apiAvailable = false;
    await page.context().setOffline(true);
    await page.getByRole("button", { name: "记一笔" }).click();
    await page.getByRole("button", { name: "9", exact: true }).click();
    await page.getByLabel("备注").fill("离线午餐");
    await page.getByLabel("备注").press("Tab");
    await page.getByRole("button", { name: "完成记账" }).click();
    await expect(page.getByText("离线午餐")).toBeVisible();
    await expect(page.getByText(/条账目未同步云端/)).toBeVisible();
    await expect(page.getByRole("img", { name: "未同步云端" })).toBeVisible();
  });

  test("03-恢复网络后手动同步并清除待同步标识", async ({ page }) => {
    const state = await mockApi(page);
    await 登录(page);
    state.apiAvailable = false;
    await page.context().setOffline(true);
    await page.getByRole("button", { name: "记一笔" }).click();
    await page.getByRole("button", { name: "3", exact: true }).click();
    await page.getByLabel("备注").press("Tab");
    await page.getByRole("button", { name: "完成记账" }).click();
    await page.context().setOffline(false);
    await expect(page.getByRole("button", { name: /立即同步/ })).toBeVisible();
    state.apiAvailable = true;
    await page.getByRole("button", { name: /立即同步/ }).click();
    await expect(page.getByText(/未同步云端/)).not.toBeVisible();
  });
});
