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

test("Pasting a balanced thread destination consumes the whole link", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Paste thread link", messages: ["Start a follow-up"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await browser.evaluate(() => {
    const environmentId = decodeURIComponent(window.location.pathname.split("/")[1]!);
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", `[Review](t3-thread://v2/${environmentId}/feature(test))`);
    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 }));
  });
  await composer.getByText("Review", { exact: true }).waitFor();
  await app.screenshot("balanced-parentheses-paste");
  const pasted = await browser.evaluate(() => {
    const editor = document.querySelector('[contenteditable="true"][role="textbox"]') ?? document.querySelector('[contenteditable="true"]');
    const link = editor?.querySelector("a");
    return { text: (editor as HTMLElement)?.innerText.trim(), href: link?.getAttribute("href") };
  });
  expect(pasted.text).toBe("Review");
  expect(pasted.href).toBe(`/${await browser.evaluate(() => decodeURIComponent(window.location.pathname.split("/")[1]!))}/feature(test)`);
});
