/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";

import { test, WEB } from "./t3.ts";

async function documentWithContents() {
  const opening =
    '<w:p><w:hyperlink w:anchor="appendix"><w:r><w:t>Appendix</w:t></w:r></w:hyperlink></w:p>';
  const chapters = Array.from(
    { length: 19 },
    (_, i) =>
      `<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>Chapter ${i + 1}</w:t></w:r></w:p>` +
      "<w:p><w:r><w:t>Chapter text</w:t></w:r></w:p>".repeat(19),
  ).join("");
  const appendix =
    '<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:bookmarkStart w:id="1" w:name="appendix"/><w:r><w:t>Appendix details</w:t></w:r><w:bookmarkEnd w:id="1"/></w:p>';
  return new JSZip()
    .file(
      "[Content_Types].xml",
      '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>',
    )
    .file(
      "_rels/.rels",
      '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
    )
    .file(
      "word/document.xml",
      `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${opening}${chapters}${appendix}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>`,
    )
    .generateAsync({ type: "uint8array" });
}

test(
  "Scrolling after a pending DOCX contents link preserves the reading position",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await t3.project("demo", { "guide.docx": await documentWithContents() });
    await browser.addInitScript(() => {
      const postMessage = Worker.prototype.postMessage;
      Worker.prototype.postMessage = function (
        this: Worker,
        request: { method?: string },
        options?: Transferable[] | StructuredSerializeOptions,
      ) {
        // Keep the worker's real provisional layout until the reader follows the link.
        if (request.method === "layout") {
          Worker.prototype.postMessage = postMessage;
          document.addEventListener(
            "resume-docx-layout",
            () => Reflect.apply(postMessage, this, [request, options]),
            { once: true },
          );
          document.documentElement.dataset.docxLayoutHeld = "true";
          return;
        }
        Reflect.apply(postMessage, this, [request, options]);
      };
    });
    await t3.open();
    await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("guide.docx");
    await screen.getByRole("option", "guide.docx", { exact: false }).tap();
    await browser.locator('html[data-docx-layout-held="true"]').waitFor({
      state: "attached",
      timeout: 40_000,
    });
    await screen.getByRole("link", "Appendix", { exact: true }).tap();
    const bounds = await browser.evaluate(() => {
      const rect = document.querySelector("[data-office-pages]")!.getBoundingClientRect();
      return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
    });
    await browser.mouse.move(bounds.x, bounds.y);
    await browser.mouse.wheel(0, 320);
    await browser.evaluate(() => new Promise<void>((resolve) => {
      const element = document.querySelector("[data-office-pages]")!;
      if (element.scrollTop > 0) resolve();
      else element.addEventListener("scroll", () => resolve(), { once: true });
    }));
    await app.screenshot("reader-scroll-before-layout-finishes");
    await browser.evaluate(() => {
      document.dispatchEvent(new Event("resume-docx-layout"));
      return null;
    });
    await screen.getByText(/^21 pages ·/).waitFor();
    await browser.evaluate(() => new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
    try {
      await expect.poll(() => browser.evaluate(() => {
        const scroller = document.querySelector("[data-office-pages]")!;
        return Math.abs(scroller.scrollTop - 320) < 2;
      })).toBe(true);
    } finally {
      await app.screenshot("reading-position-after-layout-finishes");
    }
  },
);
