/// <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: 600 },
    (_, 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(30),
  ).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("Returning to the top after scrolling cancels a waiting DOCX contents link", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "guide.docx": await documentWithContents() });
    const thread = await t3.thread({ project, title: "Read guide", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", {exact: true}).waitFor();
    await browser.keyboard.press("Control+p");
    const readme = screen.getByRole("option", "README.md", {exact: false});
    await readme.waitFor();
    await screen.getByPlaceholder("Search files…").fill("guide.docx");
    await readme.waitFor({state: "hidden"});
    await screen.getByRole("option", "guide.docx", { exact: false }).waitFor();
    await browser.keyboard.press("Enter");
    await screen.getByRole("link", "Appendix", { exact: true }).waitFor();
    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 screen.getByRole("link", "Appendix", { exact: true }).tap();
    await browser.mouse.move(bounds.x, bounds.y);
    await browser.mouse.wheel(0, 600);
    await browser.evaluate(async () => {
      await new Promise<void>((resolve) => {
        const el = document.querySelector("[data-office-pages]")!;
        if (el.scrollTop > 0) return resolve();
        el.addEventListener("scroll", () => resolve(), {once: true});
      });
      return null;
    });
    await browser.mouse.wheel(0, -600);
    await browser.evaluate(async () => {
      const el = document.querySelector("[data-office-pages]")!;
      if (el.scrollTop !== 0) await new Promise<void>((resolve) => {
        const check = () => { if (el.scrollTop === 0) { el.removeEventListener("scroll", check); resolve(); } };
        el.addEventListener("scroll", check);
      });
      return null;
    });
    await app.screenshot("returned-to-top-during-layout");
    await screen.getByText(/^602 pages/).waitFor({timeout: 60000});
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 3000)); return null; });
    await app.screenshot("reading-position-after-layout");
    expect(await browser.evaluate(() => document.querySelector("[data-office-pages]")!.scrollTop)).toBe(0);
  },
);
