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

test("Thread links stay live after indented fence-like code", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const linked = await t3.thread({ project, title: "Release notes", messages: ["Draft the notes"] });
  await t3.open(linked);
  const environmentId = await browser.evaluate(() => decodeURIComponent(window.location.pathname.split("/")[1]!));
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  const composer = screen.getByRole("textbox");
  await composer.tap();
  const results: boolean[] = [];
  for (const [label, prefix] of [
    ["control-simple-link", "See "],
    ["heading-indented-code", "Intro\n# Example\n    ~~~\n    example\n\nSee "],
    ["control-without-fence-like-line", "Intro\n# Example\n    example\n\nSee "],
    ["blank-line-indented-code", "Intro\n\n    ~~~\n    example\n\nSee "],
  ]) {
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+a");
    await browser.keyboard.press("Backspace");
    await browser.evaluate(({threadId, prefix, environmentId}: {threadId: string; prefix: string; environmentId: string}) => {
      const href = `https://app.t3.codes/threads/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`;
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", prefix + 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, prefix, environmentId });
    await composer.getByText("See", { exact: false }).waitFor();
    if (label === "control-simple-link") await composer.getByText("Release notes", { exact: true }).waitFor();
    await app.screenshot(label!);
    results.push(await browser.evaluate(() => {
      const editor = document.querySelector('[data-testid="composer-editor"]');
      return editor?.textContent?.includes("Release notes") ?? false;
    }));
  }
  expect(results).toEqual([true, true, true, true]);
});
