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

test("Hosted dotted thread links preserve the full ID and URL boundaries", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Link paste demo");
  const thread = await t3.thread({ project, title: "Hosted link paste", messages: ["Ready to check pasted links."] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  const results = [];
  for (const [label, suffix, prefix] of [
    ["literal-dot", "task.foo", ""],
    ["sentence-punctuation", "task.foo.", "See "],
    ["query-unchanged", "task.foo?prompt=go", ""],
    ["extra-path-unchanged", "task.foo/extra", ""],
    ["hyphen-control", "task-foo", ""],
    ["encoded-dot-control", "task%2Efoo", ""],
  ]) {
    await composer.tap();
    await composer.press("ControlOrMeta+a");
    await composer.press("Backspace");
    await browser.evaluate(({ suffix, prefix }) => {
      const env = decodeURIComponent(location.pathname.split("/")[1]!);
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", `${prefix}https://app.t3.codes/threads/${env}/${suffix}`);
      document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    }, { suffix, prefix });
    await composer.getByText(/Thread|https:\/\/app/).first().waitFor();
    await app.screenshot(label!);
    results.push(await browser.evaluate(() => {
      const editor = document.querySelector('[role="textbox"]')!;
      return { text: editor.textContent, links: Array.from(editor.querySelectorAll("a")).map(a => decodeURIComponent(a.getAttribute("href")!).split("/").pop()) };
    }));
  }
  expect(results.map(r => r.links)).toEqual([["task.foo"], ["task.foo"], [], [], ["task-foo"], ["task.foo"]]);
  expect(results[1]!.text).toMatch(/^See\s*Thread\s*\.$/);
  expect(results[2]!.text).toMatch(/task\.foo\?prompt=go$/);
  expect(results[3]!.text).toMatch(/task\.foo\/extra$/);
});
