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

function pdf() {
  const content = "BT /F1 18 Tf 40 720 Td (Quarterly Planning Notes) Tj 0 -32 Td (Page text line two for selection.) Tj 0 -32 Td (Third line of PDF content.) Tj ET";
  const objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 1 /Kids [3 0 R] >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>", `<< /Length ${content.length} >>\nstream\n${content}\nendstream`, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"];
  let source = "%PDF-1.4\n";
  const offsets: number[] = [];
  for (const [i, object] of objects.entries()) { offsets.push(source.length); source += `${i+1} 0 obj\n${object}\nendobj\n`; }
  const xref = source.length;
  source += `xref\n0 6\n0000000000 65535 f \n${offsets.map(o => `${String(o).padStart(10, "0")} 00000 n \n`).join("")}trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
  return Buffer.from(source);
}

test("Select all in PDF selects only mounted page text", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("PDF Demo", { "planning.pdf": pdf() });
  const thread = await t3.thread({ project, title: "PDF selection", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "planning.pdf").tap();
  await browser.locator('[data-pdf-text-layer] span').first().waitFor({ timeout: 60000 });
  await screen.getByText("Quarterly Planning Notes", { exact: true }).tap();
  await browser.keyboard.press("Control+a");
  await app.screenshot("pdf-select-all");
  const selection = await browser.evaluate(() => window.getSelection()?.toString().replace(/\s+/g, " ").trim());
  await expect(selection).toBe("Quarterly Planning Notes Page text line two for selection. Third line of PDF content.");
});
