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

test("Thread link after an unclosed list fence becomes a chip", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const linked = await t3.thread({ project, title: "Release checklist", messages: ["Start checklist"] });
  const notes = await t3.thread({ project, title: "Release notes", messages: ["Draft notes"] });
  await t3.open(notes);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  const paste = async (withList: boolean) => browser.evaluate(({ threadId, withList }) => {
    const env = decodeURIComponent(window.location.pathname.split("/")[1]!);
    const link = `See [Release checklist](https://app.t3.codes/threads/${env}/${encodeURIComponent(threadId)})`;
    const data = new DataTransfer();
    data.setData("text/plain", withList ? "- ```text\n  example\n\n" + link : link);
    const editor = document.activeElement;
    if (!editor?.matches('[contenteditable="true"]')) throw new Error("Composer is not focused");
    editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    return null;
  }, { threadId: linked.threadId, withList });
  await paste(false);
  await composer.getByText("Release checklist", { exact: true }).waitFor();
  await app.screenshot("control-thread-link");
  await browser.keyboard.press("Control+a");
  await browser.keyboard.press("Backspace");
  await paste(true);
  await app.screenshot("thread-link-after-list-fence");
  await expect(browser.locator('[role="textbox"] [data-slot="context-chip-label"]')).toHaveText("Release checklist");
});
