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

test("Query-only EPUB chapter links scroll to the current chapter anchor", WEB, async ({ t3, app, screen, browser }) => {
  const book = await new JSZip()
    .file("mimetype", "application/epub+zip")
    .file("META-INF/container.xml", '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>')
    .file("book.opf", '<package version="3.0"><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
    .file("chapter.xhtml", `<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Chapter links</h1><p><a href="#note">fragment-only link</a></p><p><a href="?x=1#note">query link</a></p>${Array.from({length:80}, (_, i) => `<p>Filler paragraph ${i+1}: reading down to the note.</p>`).join("")}<p id="note">THE NOTE PARAGRAPH (target)</p><p>End of chapter.</p></body></html>`)
    .generateAsync({ type: "uint8array", compression: "DEFLATE" });
  const project = await t3.project("epub-demo", { "repro.epub": book });
  const startThread = async () => {
    for (let attempt = 0; ; attempt++) {
      try {
        return await t3.thread({ project, title: "EPUB chapter navigation", messages: ["Start"] });
      } catch (error) {
        if (attempt >= 9 || !String(error).includes("not advertised by provider devReplay")) throw error;
      }
    }
  };
  const thread = await startThread();
  await browser.setViewport({ width: 1440, height: 1000 });
  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("repro.epub");
  await screen.getByRole("option", "repro.epub", { exact: false }).tap();
  await browser.locator('iframe[title^="repro.epub"]').waitFor({ timeout: 120_000 });
  await browser.evaluate(() => new Promise<void>((resolve) => {
    const ready = () => {
      const doc = document.querySelector<HTMLIFrameElement>('iframe[title^="repro.epub"]')?.contentDocument;
      if (doc?.getElementById("note")) resolve(); else requestAnimationFrame(ready);
    };
    ready();
  }));
  await app.screenshot("chapter-before-query-click");
  await browser.evaluate(() => {
    const doc = document.querySelector<HTMLIFrameElement>('iframe[title^="repro.epub"]')!.contentDocument!;
    const query = Array.from(doc.querySelectorAll("a")).find(a => a.textContent === "query link")!;
    query.click();
    return null;
  });
  try {
    await expect.poll(() => browser.evaluate(() => {
      const doc = document.querySelector<HTMLIFrameElement>('iframe[title^="repro.epub"]')!.contentDocument!;
      const note = doc.getElementById("note")!.getBoundingClientRect();
      return note.top >= 0 && note.bottom <= doc.documentElement.clientHeight;
    })).toBe(true);
  } finally {
    await app.screenshot("chapter-after-query-click");
  }
});
