/// <reference lib="dom" />
import { readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const RTF = String.raw`{\rtf1\ansi
Before table\par
\trowd\cellx4500\cellx9000
\pard\intbl\itap2 Inner A\nestcell Inner B\nestcell
{\*\nesttableprops\trowd\itap2\cellx2250\cellx4500\nestrow}{\nonesttables\par}
\pard\intbl\itap1\cell Outer B\cell\row
\trowd\cellx4500\cellx9000
\pard\intbl Row2 A\cell Row2 B\cell\row
\pard After table\par}`;

test("Fresh RTF attachment separates nested cells", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Nested table");
  const thread = await t3.thread({ project, title: "RTF attachment extraction", messages: ["Start"] });
  await browser.addInitScript(() => {
    const done = Promise.withResolvers<void>();
    (window as unknown as { uploadDone: Promise<void> }).uploadDone = done.promise;
    const send = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function (...args) {
      this.addEventListener("load", () => { if (this.status >= 200 && this.status < 300) done.resolve(); }, { once: true });
      return send.apply(this, args);
    };
  });
  await t3.open(thread);
  await screen.getByRole("textbox").tap();
  await browser.evaluate((rtf) => {
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([rtf], "nested-table.rtf", { type: "application/rtf" }));
    document.activeElement?.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
  }, RTF);
  await screen.getByRole("button", "File attachment, nested-table.rtf", { exact: false }).waitFor();
  await browser.evaluate(() => (window as unknown as { uploadDone: Promise<void> }).uploadDone.then(() => null));
  // Upload completion means the server has written its immutable extraction sidecar.
  const dir = join(T3_HOME, "userdata", "attachments");
  const files = await readdir(dir, { recursive: true });
  const sidecar = files.find((file) => file.endsWith(".rtf.txt"));
  if (!sidecar) throw new Error("Fresh attachment extraction sidecar missing");
  const text = await readFile(join(dir, sidecar), "utf8");
  // Show the actual server-produced text in the app's normal file viewer.
  await writeFile(join(project, "extracted-attachment.txt"), text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-attachment.txt");
  await screen.getByRole("option", "extracted-attachment.txt", { exact: false }).tap();
  await screen.getByText("Before table", { exact: false }).waitFor();
  await app.screenshot("extracted-attachment-text");
  expect(text).toBe("Before table\nInner A Inner B\n\tOuter B\t\nRow2 A\tRow2 B\t\nAfter table");
});
