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

test("Mac Roman RTF previews decode accented characters", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("RTF samples", {
    "mac-bare.rtf": String.raw`{\rtf1\mac Caf\'8e Cr\'8fme}`,
    "mac-cp10000.rtf": String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`,
    "control-1252.rtf": String.raw`{\rtf1\ansi\ansicpg1252 Caf\'e9 Cr\'e8me}`,
  });
  const thread = await t3.thread({ project, title: "RTF document previews", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  const results: string[] = [];
  for (const name of ["mac-bare.rtf", "mac-cp10000.rtf", "control-1252.rtf"]) {
    await screen.getByRole("treeitem", name).tap();
    await browser.locator(`iframe[title^="${name}"], [role="alert"]`).first().waitFor({ timeout: 60000 });
    results.push(await browser.evaluate((name) => {
      const frame = document.querySelector<HTMLIFrameElement>(`iframe[title^="${name}"]`);
      if (!frame) return document.querySelector('[role="alert"]')?.textContent ?? "";
      return new DOMParser().parseFromString(frame.srcdoc, "text/html").body.textContent ?? "";
    }, name));
    await app.screenshot(name.replace(".rtf", ""));
  }
  expect(results).toEqual(["Café Crème", "Café Crème", "Café Crème"]);
});
