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

test("EPUB fallback links preserve the authored and current spine entries", WEB, async ({t3, app, screen, browser}) => {
 const html = (body: string) => `<html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>${body}</body></html>`;
 const book = await new JSZip()
 .file("mimetype", "application/epub+zip", {compression:"STORE"})
 .file("META-INF/container.xml", '<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
 .file("book.opf", `<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">fallback-proof</dc:identifier><dc:title>Fallback link guide</dc:title><dc:language>en</dc:language><meta property="dcterms:modified">2026-12-04T00:00:00Z</meta></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="intro" href="intro.xhtml" media-type="application/xhtml+xml"/><item id="chapter" href="chapter.txt" media-type="text/plain" fallback="fallback"/><item id="fallback" href="fallback.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="intro"/><itemref idref="chapter"/><itemref idref="fallback"/></spine></package>`)
 .file("nav.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="intro.xhtml">Intro</a></li><li><a href="chapter.txt">Reference</a></li><li><a href="fallback.xhtml">Explicit fallback</a></li></ol></nav></body></html>')
 .file("intro.xhtml", html('<h1>Intro</h1><p><a href="chapter.txt">Read Reference</a></p>'))
 .file("chapter.txt", "Non-core content")
 .file("fallback.xhtml", html('<h1>Reference details</h1><p id="note">Shared content, distinct spine entries.</p><p><a href="#note">Fragment only</a></p><p><a href="?view=reading#note">Query only</a></p><p><a href="fallback.xhtml">Explicit fallback file</a></p>'))
 .generateAsync({type:"uint8array"});
 const project = await t3.project("books", {"fallback-book.epub":book});
 const thread = await t3.thread({project,title:"Read fallback guide",messages:["Start"]});
 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("fallback-book.epub");
 await screen.getByRole("option","fallback-book.epub",{exact:false}).tap();
 const frame = browser.frameLocator('iframe[title^="fallback-book.epub"]');
 await frame.getByRole("link","Read Reference").waitFor({timeout:120000});
 await screen.getByRole("button","Maximize panel",{exact:true}).tap();
 await screen.getByRole("button","Hide file explorer",{exact:true}).tap();
 const results: Record<string, boolean> = {};
 const chapter = async () => browser.evaluate(() => Array.from(document.querySelectorAll('[role="status"]')).map(x=>x.textContent).find(x=>x?.includes("Chapter ")) ?? "");
 const clickLink = async (name: string) => {
  const box = await frame.getByRole("link",name,{exact:true}).boundingBox();
  if (!box) throw new Error(`Missing link ${name}`);
  await browser.mouse.move(box.x+box.width/2,box.y+box.height/2);
  await browser.mouse.down();
  await browser.mouse.up();
 };
 await screen.getByRole("combobox","Chapter",{exact:true}).tap();
 results.authoredLabel = await screen.getByRole("option","Reference",{exact:true}).isVisible();
 await app.screenshot("01-authored-contents");
 await browser.keyboard.press("Escape");
 await clickLink("Read Reference");
 // Read the state after the real click; waiting for the target would stop the broken-side capture.
 await app.screenshot("02-read-reference");
 results.originalHref = (await chapter()).includes("Chapter 2 of 3");
 if (!(await chapter()).includes("Chapter 2 of 3")) await screen.getByRole("button","Next chapter",{exact:true}).tap();
 await frame.getByText("Reference details",{exact:true}).waitFor();
 for (const n of [2,3]) {
  for (const link of ["Fragment only","Query only"]) {
   await clickLink(link);
   await app.screenshot(`${n}-${link.replaceAll(" ","-")}`);
   results[`${n}-${link}`] = (await chapter()).includes(`Chapter ${n} of 3`);
   // Paging restores the later entry after the broken resolver jumps to the first shared entry.
   if (!(await chapter()).includes(`Chapter ${n} of 3`)) {
    await screen.getByRole("button","Next chapter",{exact:true}).tap();
    await frame.getByText("Reference details",{exact:true}).waitFor();
   }
  }
  if (n===2) {
   await clickLink("Explicit fallback file");
   await app.screenshot("03-explicit-fallback-file");
   results.explicitSpine = (await chapter()).includes("Chapter 3 of 3");
   if (!(await chapter()).includes("Chapter 3 of 3")) await screen.getByRole("button","Next chapter",{exact:true}).tap();
  }
 }
 expect(results).toEqual({authoredLabel:true,originalHref:true,"2-Fragment only":true,"2-Query only":true,explicitSpine:true,"3-Fragment only":true,"3-Query only":true});
});
