import { expect, test } from "@playwright/test";
import { deleteBook, importEpub } from "./fixtures";

test("persists paragraph edits, include choices, rename, split, and merge", async ({ page }) => {
  const title = `听阅校对验收-${Date.now()}`;
  const editedText = "这是人工修正后的第一段正文。";
  const skippedText = "你好，这是中文端到端验收句。";
  const renamedChapter = "人工重命名章节";
  let bookId: string | null = null;
  try {
    bookId = await importEpub(page, title);

    const firstParagraph = page.getByRole("textbox", { name: "第 1 段正文" });
    await firstParagraph.fill(editedText);
    await page.getByRole("checkbox").nth(1).uncheck();

    page.once("dialog", (dialog) => dialog.accept(renamedChapter));
    await page.getByRole("button", { name: "重命名" }).click();
    await expect(page.getByText(renamedChapter, { exact: true })).toBeVisible();

    page.once("dialog", (dialog) => dialog.accept("拆分后章节"));
    await page.getByRole("button", { name: "从这里拆分" }).nth(2).click();
    await expect(page.getByText("拆分后章节", { exact: true })).toBeVisible();
    await page.getByRole("button", { name: "合并下一章" }).click();

    await page.getByRole("button", { name: "保存修改" }).click();
    await expect(page.getByText("修改已保存。变更段落的旧语音已失效，其余语音会继续复用。")).toBeVisible();
    await page.reload();
    await expect(page.getByRole("heading", { name: "可朗读正文" })).toBeVisible();
    await expect(page.getByText(renamedChapter, { exact: true })).toBeVisible();
    await expect(page.getByRole("textbox", { name: "第 1 段正文" })).toHaveValue(editedText);
    await expect(page.getByRole("checkbox").nth(1)).not.toBeChecked();

    await page.getByRole("link", { name: "立即收听" }).click();
    await expect(page.getByLabel("逐句正文")).toContainText(editedText);
    await expect(page.getByLabel("逐句正文").locator(".skipped")).toContainText(skippedText);
  } finally {
    await deleteBook(page, bookId);
  }
});
