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

const MESSAGE = "This file is not UTF-8 text. Open it in another app to view its contents.";

test("Large cp1252 attachments show the readable unsupported-text message", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("preview-demo");
  const thread = await t3.thread({ project, title: "Text preview", model: "default", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByRole("button", "Attach files", { exact: true }).waitFor({ timeout: 60000 });
  for (const [name, rows] of [["small-cp1252.csv", 5000], ["large-cp1252.csv", 90000]] as const) {
    await browser.evaluate(({ name, rows }) => {
      const text = "name,city\r\n" + "caf\u00e9,M\u00fcnchen,123\r\n".repeat(rows);
      const bytes = Uint8Array.from(text, (char) => char.charCodeAt(0));
      const transfer = new DataTransfer();
      transfer.items.add(new File([bytes], name, { type: "text/csv" }));
      const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
      input.files = transfer.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
    }, { name, rows });
    await screen.getByRole("button", name, { exact: false }).first().tap();
    await screen.getByRole("button", "Try again", { exact: true }).waitFor({ timeout: 60000 });
    await app.screenshot(name.startsWith("large") ? "large-preview" : "small-preview");
    await expect(screen.getByText(MESSAGE, { exact: true })).toBeVisible();
    await screen.getByRole("button", "Remove from draft", { exact: true }).tap();
  }
});
