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

const rtf = String.raw`{\rtf1\ansi\uc11\u945abcdefghijkZ}`;

test("RTF Unicode skips all eleven fallback bytes in both previews", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("RTF sample", { "fallback.rtf": rtf });
  const thread = await t3.thread({ project, title: "Review fallback", messages: ["Start"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Review fallback").waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("fallback.rtf");
  await screen.getByRole("option", "fallback.rtf", { exact: false }).waitFor();
  await screen.getByRole("option", "README.md", { exact: false }).waitFor({ state: "hidden" });
  await browser.keyboard.press("Enter");
  await screen.getByText("1 page", { exact: false }).waitFor({ timeout: 120_000 });
  const body = browser.frameLocator('iframe[title^="fallback.rtf"]').locator("body");
  await body.waitFor();
  const workspaceText = await body.textContent();
  await app.screenshot("workspace-rtf-preview");
  await screen.getByRole("button", "Close fallback.rtf", { exact: true }).tap();
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(({ selector, text }) => {
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    const files = new DataTransfer();
    files.items.add(new File([text], "fallback.rtf", { type: "application/rtf" }));
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, { selector: input, text: rtf });
  await screen.getByRole("button", /^File attachment, fallback\.rtf,/).tap();
  await screen.getByRole("dialog", "fallback.rtf").waitFor();
  const attachmentBody = browser.frameLocator('iframe[title^="fallback.rtf"]').locator("body");
  await attachmentBody.waitFor();
  const attachmentText = await attachmentBody.textContent();
  await app.screenshot("attachment-rtf-preview");
  expect({ workspaceText, attachmentText }).toEqual({ workspaceText: "αZ", attachmentText: "αZ" });
});
