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

test("Repeating an empty-file attachment shows its error after dismissal", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Attachment demo");
  const thread = await t3.thread({project, title: "Saved attachment thread", messages: ["first"]});
  await browser.setViewport({width: 1280, height: 900});
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  const attach = async (name: string) => {
    await browser.evaluate(async (name) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
      if (!input) throw new Error("Composer attachment input missing");
      const data = new DataTransfer();
      data.items.add(new File([], name, {type: "text/plain"}));
      input.files = data.files;
      input.dispatchEvent(new Event("change", {bubbles: true}));
      await new Promise(resolve => setTimeout(resolve, 500));
    }, name);
  };
  const results: boolean[] = [];
  for (const mode of ["saved", "draft"]) {
    if (mode === "draft") {
      await screen.getByRole("button", "New thread", {exact: false}).first().tap();
      await screen.getByRole("textbox").waitFor();
    }
    await attach("empty-notes.txt");
    await screen.getByText("'empty-notes.txt' is empty or could not be read.", {exact: true}).waitFor();
    await app.screenshot(`${mode}-initial-error`);
    await screen.getByRole("button", "Dismiss error", {exact: true}).tap();
    await screen.getByRole("button", "Dismiss error", {exact: true}).waitFor({state: "hidden"});
    await attach("empty-notes.txt");
    await attach("empty-notes.txt");
    await app.screenshot(`${mode}-repeated-error`);
    results.push(await browser.evaluate(() => document.body.innerText.includes("'empty-notes.txt' is empty or could not be read.")));
    await attach("other-empty.txt");
    await screen.getByText("'other-empty.txt' is empty or could not be read.", {exact: true}).waitFor();
    await attach("empty-notes.txt");
    await app.screenshot(`${mode}-original-after-control`);
    results.push(await browser.evaluate(() => document.body.innerText.includes("'empty-notes.txt' is empty or could not be read.")));
  }
  expect(results).toEqual([true, true, true, true]);
});
