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

function pdf() {
  const cmap = (from: string, to: string) => `/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def
/CMapName /Unicode def
/CMapType 2 def
1 begincodespacerange
<00> <FF>
endcodespacerange
1 beginbfchar
<${from}> <${to}>
endbfchar
endcmap
CMapName currentdict /CMap defineresource pop
end
end`;
  const stream = (s: string) => `<< /Length ${s.length} >>\nstream\n${s}\nendstream`;
  const objects = [
    "<< /Type /Catalog /Pages 2 0 R >>",
    "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
    "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R /F2 5 0 R >> >> /Contents 6 0 R >>",
    "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 7 0 R >>",
    "<< /Type /Font /Subtype /Type1 /BaseFont /Courier /ToUnicode 8 0 R >>",
    stream("BT /F1 48 Tf 50 700 Td (A) Tj /F2 48 Tf (B) Tj ET"),
    stream(cmap("41", "039F")), stream(cmap("42", "03A3")),
  ];
  let out = "%PDF-1.4\n";
  const offsets = [0];
  objects.forEach((obj, i) => { offsets.push(out.length); out += `${i+1} 0 obj\n${obj}\nendobj\n`; });
  const xref = out.length;
  out += `xref\n0 9\n0000000000 65535 f \n`;
  for (const offset of offsets.slice(1)) out += `${String(offset).padStart(10,"0")} 00000 n \n`;
  out += `trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(out);
}

test("Greek PDF search highlights both split text runs", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Greek PDF search", {"greek-split.pdf": pdf()});
  const thread = await t3.thread({project, title: "Greek PDF search", messages: ["Start"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "greek-split.pdf").tap();
  await browser.locator("[data-pdf-text-layer] span").first().waitFor({timeout: 60000});
  const find = screen.getByRole("searchbox", "Find in PDF");
  for (const [query,label] of [["ΟΣ","uppercase-sigma"],["ος","final-sigma"],["οσ","lowercase-sigma"],["Σ","sigma-alone"]]) {
    await find.fill(query);
    await screen.getByRole("status").filter({hasText:"1/1"}).waitFor();
    await app.screenshot(label);
    await expect.poll(() => browser.evaluate(() => Array.from(document.querySelectorAll("[data-pdf-text-layer] .pdf-find-match"), e => e.textContent))).toEqual(query === "Σ" ? ["Σ"] : ["Ο", "Σ"]);
  }
});
