import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, test, WEB } from "./t3.ts";

test("Dropped remote thread filenames retain combining marks", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("destination");
  const destination = await t3.thread({ project, title: "New thread", messages: ["Start"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const remote = makeState(SECOND_HOME).state;
    const source = await remote.project("source");
    const titles = ["नया फ़ीचर जोड़ें", "Cafe\u0301 notes/x"];
    const threads = [];
    for (const title of titles) threads.push(await remote.thread({ project: source, title, messages: ["Start"] }));
    await browser.setViewport({ width: 1440, height: 900 });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").waitFor({ timeout: 90_000 });
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog", "Add Environment", { exact: true });
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await dialog.waitFor({ state: "hidden", timeout: 90_000 });
    await t3.open(destination);
    for (const thread of threads) {
      const row = browser.locator(`[data-sidebar-row$=":${thread.threadId}"]`);
      await row.waitFor();
      const points = await browser.evaluate((id) => {
        const row = document.querySelector(`[data-sidebar-row$=":${id}"]`)!;
        const target = document.querySelector('[data-thread-context-drop]')!;
        const a = row.getBoundingClientRect(), b = target.getBoundingClientRect();
        return { from: { x: a.x + a.width / 2, y: a.y + a.height / 2 }, to: { x: b.x + b.width / 2, y: b.y + b.height / 2 } };
      }, thread.threadId);
      await screen.swipe({ ...points, duration: 1000 });
      await screen.getByRole("button", /File attachment, .*jsonl/).nth(threads.indexOf(thread)).waitFor();
    }
    await app.screenshot("dropped-thread-attachment-names");
    await expect(screen.getByRole("button", /File attachment, नया फ़ीचर जोड़ें-.*\.jsonl/)).toBeVisible();
    await expect(screen.getByRole("button", /File attachment, Cafe\u0301 notes_x-.*\.jsonl/)).toBeVisible();
  } finally { await server.stop(); }
});
