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

function pdf() {
  const content = "BT /F1 22 Tf 60 700 Td (Project budget) Tj 0 -40 Td (Review budget before approval.) Tj ET";
  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 >> >> /Contents 5 0 R >>", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", `<< /Length ${content.length} >>\nstream\n${content}\nendstream`];
  let data = "%PDF-1.4\n";
  const offsets = [0];
  for (const [i, object] of objects.entries()) { offsets.push(data.length); data += `${i + 1} 0 obj\n${object}\nendobj\n`; }
  const xref = data.length;
  data += `xref\n0 6\n0000000000 65535 f \n${offsets.slice(1).map(n => `${String(n).padStart(10, "0")} 00000 n \n`).join("")}trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(data);
}

test("Escape clears PDF search before dismissing the Files sheet", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("PDF demo", { "plan.pdf": pdf() });
  const thread = await t3.thread({ project, title: "Review project plan", messages: ["Start"] });
  await browser.setViewport({ width: 900, height: 800 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByPlaceholder("Search files", { exact: true }).fill("plan.pdf");
  await screen.getByRole("treeitem", "plan.pdf").tap();
  const find = screen.getByRole("searchbox", "Find in PDF");
  await find.waitFor({ timeout: 120_000 });
  await find.fill("budget");
  await screen.getByRole("status").filter({ hasText: "1/1" }).waitFor();
  await app.screenshot("before-escape");
  await find.press("Escape");
  await app.screenshot("after-first-escape");
  await expect(find).toBeVisible();
  await expect(find).toHaveValue("");
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true, cancelable: true }));
    return null;
  });
  await app.screenshot("after-held-repeat");
  await expect(find).toBeVisible();
  await find.press("Escape");
  await app.screenshot("after-fresh-second-escape");
  await expect(find).not.toBeVisible();
});
