import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

async function odt(item: boolean) {
  return new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("content.xml", `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3">
      <office:automatic-styles><text:list-style style:name="Steps"><text:list-level-style-number text:level="1" style:num-format="1" ${item ? "" : 'text:start-value="4"'}/></text:list-style></office:automatic-styles>
      <office:body><office:text><text:p>Steps:</text:p><text:list text:style-name="Steps">
      <text:list-item ${item ? 'text:start-value="4"' : ""}><text:p>Review the draft</text:p></text:list-item>
      <text:list-item><text:p>Send the draft</text:p></text:list-item>
      </text:list></office:text></office:body></office:document-content>`)
    .generateAsync({ type: "uint8array" });
}

test("ODT previews preserve style starts and explicit item overrides", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Document review", { "steps.odt": await odt(false), "steps-item.odt": await odt(true) });
  const thread = await t3.thread({ project, title: "Review steps", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor({ state: "visible" });
  const starts: number[] = [];
  for (const file of ["steps.odt", "steps-item.odt"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, { exact: false }).tap();
    const preview = browser.frameLocator(`iframe[title^="${file}"]`);
    const list = preview.locator('ol:has(> li:first-child:has-text("Review the draft"))');
    const first = preview.locator('ol > li:first-child:has-text("Review the draft")');
    await first.waitFor({ state: "visible", timeout: 120_000 });
    starts.push(Number((await first.getAttribute("value")) ?? (await list.getAttribute("start")) ?? 1));
    await app.screenshot(file === "steps.odt" ? "style-start" : "item-start");
  }
  expect(starts).toEqual([4, 4]);
});
