/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

test("ODP slide-number fields display the slide index", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip();
  zip.file("mimetype", "application/vnd.oasis.opendocument.presentation", { compression: "STORE" });
  zip.file("META-INF/manifest.xml", `<?xml version="1.0"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.presentation"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>`);
  zip.file("content.xml", `<?xml version="1.0"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3"><office:body><office:presentation>${[1,2].map(n => `<draw:page draw:name="Slide ${n}"><draw:frame><draw:text-box><text:p>Slide <text:page-number>&lt;number&gt;</text:page-number></text:p></draw:text-box></draw:frame></draw:page>`).join("")}</office:presentation></office:body></office:document-content>`);
  const project = await t3.project("presentation", { "slidenum.odp": await zip.generateAsync({ type: "uint8array" }) });
  const thread = await t3.thread({ project, title: "Review slide numbers", model: "default", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText("This turn is a replay. It costs nothing, so send it again as often as you need.", { exact: true }).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("slidenum.odp");
  await screen.getByRole("option", "slidenum.odp", { exact: false }).tap();
  const body = () => browser.evaluate(() => Array.from(document.querySelectorAll("iframe")).map(f => new DOMParser().parseFromString(f.srcdoc, "text/html").body.textContent?.trim()).find(t => t?.startsWith("Slide ")) ?? "");
  await browser.locator('iframe[title^="slidenum.odp:"]').waitFor({ timeout: 120_000 });
  const first = await body();
  await app.screenshot("slide-1");
  await screen.getByRole("button", "Next slide", { exact: true }).tap();
  await screen.getByText("Slide 2 of 2", { exact: false }).waitFor();
  const second = await body();
  await app.screenshot("slide-2");
  await expect([first, second]).toEqual(["Slide 1", "Slide 2"]);
});
