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

const names = [
  "스크린샷 2026-11-05 오후 10.59.14.png".normalize("NFD"),
  "아주긴파일이름테스트 스크린샷 2026-11-05 오후 10.59.14.png".normalize("NFD"),
  "abcdefghijklmnopqrst👨‍👩‍👧‍👦abcdefghijklmnopqrstuvwxyz.png",
  "abcdefghijklmnopqrst🇰🇷abcdefghijklmnopqrstuvwxyz.png",
  "스크린샷 2026-11-05 오후 10.59.14 (2).png",
  "スクリーンショット 2026-11-05 22.59.14.png",
];

test("Attachment names preserve graphemes and names within the 36 character limit", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Attachment demo");
  const thread = await t3.thread({ project, title: "Attachment names", messages: ["first"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Look at ");
  await browser.evaluate(async (filenames: string[]) => {
    const bytes = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAD0lEQVR4AQEEAPv/AP8AAAMBAQCNHeWCAAAAAElFTkSuQmCC"), c => c.charCodeAt(0));
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("Attachment file input missing");
    const transfer = new DataTransfer();
    for (const name of filenames) transfer.items.add(new File([bytes], name, { type: "image/png" }));
    let completed = 0;
    let finish!: () => void;
    const uploads = new Promise<void>(resolve => { finish = resolve; });
    const send = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(body) {
      this.addEventListener("loadend", () => {
        completed++;
        if (completed === filenames.length) {
          XMLHttpRequest.prototype.send = send;
          finish();
        }
      }, { once: true });
      return send.call(this, body);
    };
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    await uploads;
  }, names);
  const chips = composer.getByRole("button", "Image attachment", { exact: false });
  await expect(chips).toHaveCount(names.length);
  await browser.evaluate(async () => {
    await document.fonts.ready;
    await new Promise<void>(resolve => {
      const ready = () => !document.querySelector('[contenteditable="true"]')!.textContent!.includes("%");
      if (ready()) return resolve();
      const observer = new MutationObserver(() => { if (ready()) { observer.disconnect(); resolve(); } });
      observer.observe(document.querySelector('[contenteditable="true"]')!, { childList: true, subtree: true, characterData: true });
    });
  });
  await app.screenshot("attachment-names");
  const labels = await browser.evaluate(() => Array.from(document.querySelectorAll('[contenteditable="true"] [aria-label^="Image attachment"]')).map(el => el.querySelector("span.max-w-72")?.textContent));
  const expected = names.map(name => {
    const parts = Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(name), p => p.segment);
    return parts.length <= 36 ? name : parts.slice(0, 21).join("") + "…" + parts.slice(-14).join("");
  });
  expect(labels).toEqual(expected);
});
