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

async function report() {
  const paragraph = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`;
  const paragraphs = (page: number) => Array.from({ length: 5 }, (_, i) => paragraph(`Page ${page} paragraph ${i + 1}: Engineering delivery remains on schedule.`)).join("");
  return new JSZip()
    .file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
    .file("_rels/.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
    .file("word/document.xml", `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${paragraph("Quarterly Engineering Brief")}${paragraph("Throughput improved after worker migration.")}${paragraphs(1)}<w:p><w:r><w:br w:type="page"/></w:r></w:p>${paragraph("Second page heading")}${paragraphs(2)}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>`)
    .generateAsync({ type: "uint8array" });
}

test("Select all in Word selects only document text", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("workspace", { "report.docx": await report() });
  const thread = await t3.thread({ project, title: "Document preview", 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("report.docx");
  await screen.getByRole("option", "report.docx", { exact: false }).tap();
  await screen.getByText("Quarterly Engineering Brief", { exact: true }).waitFor({ timeout: 120_000 });
  await screen.getByText("Second page heading", { exact: true }).waitFor();
  await screen.getByText("Quarterly Engineering Brief", { exact: true }).tap();
  await browser.keyboard.press("Control+a");
  await app.screenshot("word-document-select-all");
  const selection = await browser.evaluate(() => window.getSelection()?.toString() ?? "");
  expect(selection).toContain("Quarterly Engineering Brief");
  expect(selection).toContain("Second page heading");
  expect(selection).not.toContain("Fit to width");
  expect(selection).not.toContain("T3 Code");
  expect(selection).not.toContain("report.docx");
});
