import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Attachment previews use singular and plural count labels", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Preview samples");
  await t3.open();
  await screen.getByRole("textbox").fill("Preview attachment count samples");
  await browser.evaluate(() => {
    const data = new DataTransfer();
    for (const [name, text, type] of [
      ["one.csv", "name\nAda\n", "text/csv"],
      ["one.tsv", "name\nAda\n", "text/tab-separated-values"],
      ["two.csv", "name,age\nAda,36\nGrace,85\n", "text/csv"],
      ["one.txt", "a".repeat(1048576) + "\n", "text/plain"],
      ["two.txt", "a".repeat(524288) + "\n" + "b".repeat(524288) + "\n", "text/plain"],
    ]) data.items.add(new File([text], name, { type }));
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]')!;
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  const observed: string[] = [];
  for (const name of ["one.csv", "one.tsv", "two.csv", "one.txt", "two.txt"]) {
    await screen.getByRole("button", `File attachment, ${name},`, { exact: false }).tap();
    const text = await browser.evaluate(() => new Promise<string>((resolve) => {
      const read = () => {
        const status = document.querySelector('[role="dialog"] [role="status"]');
        const text = status?.textContent ?? "";
        if (/ · [\d.]+ [KMG]?B$/.test(text.trim())) { observer.disconnect(); resolve(text.trim()); }
      };
      const observer = new MutationObserver(read);
      observer.observe(document.body, { subtree: true, childList: true, characterData: true });
      read();
    }));
    observed.push(text);
    await app.screenshot(name.replace(".", "-"));
    await screen.getByRole("button", "Close", { exact: true }).tap();
  }
  expect(observed).toEqual([
    "1 row · 1 column · 1 KB",
    "1 row · 1 column · 1 KB",
    "2 rows · 2 columns · 1 KB",
    "1 line · 1.0 MB",
    "2 lines · 1.0 MB",
  ]);
});
