/// <reference lib="dom" />
import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, test, WEB } from "./t3.ts";

const title = "Parser rewrite review notes and the benchmark results for week 𝐀𝐥𝐩𝐡𝐚";
test("Dropped remote thread attachment preserves complete Unicode characters", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("local-demo");
  const local = await t3.thread({ project, title: "Attachment destination", messages: ["first"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const second = makeState(SECOND_HOME).state;
    const remoteProject = await second.project("remote-demo");
    const remote = await second.thread({ project: remoteProject, title, messages: ["first", "second"] });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByText(title, { exact: true }).first().waitFor({ timeout: 60_000 });
    await t3.open(local);
    await browser.locator('[contenteditable="true"]').waitFor();
    const points = await browser.evaluate((id) => {
      const row = Array.from(document.querySelectorAll('[data-sidebar-row]')).find(el => el.getAttribute('data-sidebar-row')?.includes(id));
      const editor = document.querySelector('[contenteditable="true"]');
      if (!row || !editor) throw new Error("Missing drag source or composer");
      const a = row.getBoundingClientRect(), b = editor.getBoundingClientRect();
      return { x: a.x + a.width / 2, y: a.y + a.height / 2, tx: b.x + b.width / 2, ty: b.y + b.height / 2 };
    }, remote.threadId);
    await app.screenshot("before-drop");
    await browser.mouse.move(points.x, points.y);
    await browser.mouse.down();
    for (let step = 1; step <= 20; step++) await browser.mouse.move(points.x + (points.tx - points.x) * step / 20, points.y + (points.ty - points.y) * step / 20);
    await browser.mouse.up();
    const chip = screen.getByRole("button", /Parser rewrite.*\.jsonl/).first();
    await chip.waitFor({ timeout: 60_000 });
    await chip.tap();
    await screen.getByRole("dialog", /Parser rewrite.*\.jsonl/).waitFor();
    await screen.getByRole("heading", "Loading thread context…").waitFor({ state: "hidden" });
    await app.screenshot("dropped-thread-attachment-name");
    const name = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="dialog"]')).find(el => el.textContent?.includes('Parser rewrite'))?.textContent ?? "");
    expect(name, "Attachment preview filename contains no replacement character").not.toContain("\uFFFD");
  } finally { await server.stop(); }
});
