/// <reference lib="dom" />
import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";

test("Resting composer uses singular attachment for one hidden image", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 430, height: 932 });
  await browser.emulateMedia({ colorScheme: "light" });
  const project = await t3.project("Image attachments");
  const single = await t3.thread({ project, title: "Four images", messages: ["Start"] });
  const plural = await t3.thread({ project, title: "Five images", messages: ["Start"] });
  const names: string[] = [];
  const strips: unknown[] = [];
  for (const [thread, count] of [[single, 4], [plural, 5]] as const) {
    await t3.open(thread);
    await screen.getByRole("button", "Expand composer").tap();
    await browser.evaluate(async (count) => {
      const files = new DataTransfer();
      const colors = ["red", "green", "blue", "orange", "purple"];
      for (const color of colors.slice(0, count)) {
        const canvas = document.createElement("canvas");
        canvas.width = 64; canvas.height = 64;
        const context = canvas.getContext("2d")!;
        context.fillStyle = color; context.fillRect(0, 0, 64, 64);
        const blob = await new Promise<Blob>((resolve) => canvas.toBlob((blob) => resolve(blob!), "image/png"));
        files.items.add(new File([blob], `img-${color}.png`, { type: "image/png" }));
      }
      const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
      if (!input) throw new Error("No composer file input");
      input.files = files.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
      return null;
    }, count);
    await screen.getByRole("button", count === 4 ? "Remove img-orange.png" : "Remove img-purple.png", { exact: true }).waitFor();
    await browser.mouse.move(215, 300);
    await browser.mouse.down();
    await browser.mouse.up();
    const overflow = browser.locator('[data-chat-composer-resting-images] button').last();
    await overflow.waitFor();
    const label = await browser.evaluate(() => document.querySelector('[data-chat-composer-resting-images] button:last-child')?.getAttribute("aria-label") ?? "");
    names.push(label);
    strips.push(await browser.evaluate(() => ({
      viewport: { width: innerWidth, height: innerHeight },
      language: document.documentElement.lang,
      buttons: [...document.querySelectorAll('[data-chat-composer-resting-images] button')].map(button => ({
        role: "button", accessibleName: button.getAttribute("aria-label"), text: button.textContent,
      })),
    })));
    await app.screenshot(count === 4 ? "one-hidden-image" : "two-hidden-images");
  }
  if (process.env.T3_EVIDENCE_DIR) await writeFile(join(process.env.T3_EVIDENCE_DIR, `accessibility-${Date.now()}.json`), JSON.stringify(strips, null, 2));
  expect(names).toEqual(["Show 1 more image attachment", "Show 2 more image attachments"]);
});
