/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Website destinations keep literal thread URL labels on paste", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const linked = await t3.thread({ project, title: "Release checklist", messages: ["Draft the checklist"] });
  const target = await t3.thread({ project, title: "Paste proof", messages: ["Start"] });
  await t3.open(target);
  const composer = screen.getByRole("textbox");
  const counts: number[] = [];
  for (const [label, destination] of [
    ["padded", ' https://example.com "Example"'],
    ["nested", "https://example.com/a(b(c))"],
    ["escaped", "https://example.com/a\\(b"],
    ["newline-padded", '\nhttps://example.com "Example"\n'],
    ["control", "https://example.com"],
  ]) {
    await composer.fill("");
    await composer.tap();
    await browser.evaluate(({ threadId, destination }) => {
      const environment = window.location.pathname.split("/")[1];
      const href = `https://app.t3.codes/threads/${environment}/${encodeURIComponent(threadId)}`;
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", `See [${href}](${destination}) and ${href}`);
      const editor = document.activeElement;
      if (!editor?.matches('[contenteditable="true"]')) throw new Error("Composer is not focused");
      editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    }, { threadId: linked.threadId, destination });
    const chip = composer.getByText("Release checklist", { exact: true });
    await chip.first().waitFor();
    await app.screenshot(label);
    counts.push(await chip.count());
  }
  expect(counts, "Only the standalone URL becomes a chip in every case").toEqual([1, 1, 1, 1, 1]);
});
