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

test("ODT ruby reading appears above its base word", WEB, async ({ t3, app, screen, browser }) => {
  const odt = await new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("META-INF/manifest.xml", `<?xml version="1.0"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.text"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>`)
    .file("content.xml", `<?xml version="1.0"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3"><office:automatic-styles><style:style style:name="Ru1" style:family="ruby"><style:ruby-properties style:ruby-align="center" style:ruby-position="above"/></style:style></office:automatic-styles><office:body><office:text><text:p>Read <text:ruby text:style-name="Ru1"><text:ruby-base>漢字</text:ruby-base><text:ruby-text>かんじ</text:ruby-text></text:ruby> here.</text:p></office:text></office:body></office:document-content>`)
    .generateAsync({ type: "uint8array" });
  const project = await t3.project("demo", { "ruby.odt": odt });
  const thread = await t3.thread({ project, title: "ODT pronunciation guide", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("ruby.odt");
  await screen.getByRole("option", "ruby.odt", { exact: false }).tap();
  const preview = browser.frameLocator('iframe[title^="ruby.odt"]');
  await preview.locator("p").waitFor({ state: "visible", timeout: 120_000 });
  await app.screenshot("ruby-pronunciation");
  const ruby = preview.locator("ruby");
  const rt = preview.locator("ruby rt");
  const present = await rt.count();
  let layout = { reading: null as string | null, above: false, smaller: false };
  if (present) {
    const word = await ruby.boundingBox();
    const reading = await rt.boundingBox();
    layout = {
      reading: await rt.textContent(),
      above: reading!.y + reading!.height <= word!.y + 2,
      smaller: reading!.height < word!.height,
    };
  }
  expect(layout).toEqual({ reading: "かんじ", above: true, smaller: true });
});
