/// <reference lib="dom" />
import { expect } from "e2e";

import { environmentId, runPromise, test, WEB } from "./t3.ts";

test(
  "Markdown thread links keep escaped and parenthesized titles intact",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    const source = await t3.thread({ project, title: "First thread", messages: ["First"], model: "default" });
    const target = await t3.thread({ project, title: "Second thread", messages: ["Second"], model: "default" });
    const environment = await runPromise(environmentId(app.baseUrl ?? ""));
    const href = `https://app.t3.codes/threads/${environment}/${encodeURIComponent(source.threadId)}`;
    await t3.open(target);
    const composer = screen.getByRole("textbox");
    await composer.tap();
    const paste = async (text: string) => {
      await browser.evaluate((value) => {
        const editor = document.activeElement;
        if (!(editor instanceof HTMLElement) || !editor.isContentEditable) throw new Error("The composer is not focused");
        const clipboardData = new DataTransfer();
        clipboardData.setData("text/plain", value);
        editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
      }, text);
    };
    await paste(`[Example](${href} "say \\\"hi\\\"")`);
    await expect(composer).toContainText("Example");
    await app.screenshot("escaped-quote-title");
    await expect(screen.getByLabel("Thread, First thread")).not.toBeVisible();
  },
);
