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

test("Indented fence-looking examples keep thread links literal and following prose stays active", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo-project");
  const source = await t3.thread({ project, title: "Source thread for link", messages: ["Start"] });
  const target = await t3.thread({ project, title: "Thread link examples", messages: ["Start"] });
  await t3.open(target);
  const composer = screen.getByRole("textbox");
  const results = [];
  for (const [label, indent, fence] of [
    ["four-space-fence", "    ", true],
    ["tab-fence", "\t", true],
    ["unindented-fence-control", "", true],
    ["plain-indented-link-control", "    ", false],
  ] as const) {
    await composer.fill("");
    await composer.tap();
    await browser.evaluate(({ threadId, indent, fence }) => {
      const environmentId = decodeURIComponent(window.location.pathname.split("/")[1]!);
      const link = `<t3-thread://v2/${environmentId}/${threadId}>`;
      const example = fence ? `${indent}\`\`\`md\n${indent}${link}\n${indent}\`\`\`` : `${indent}${link}`;
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", `${example}\n\nProse after the example: ${link}`);
      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: source.threadId, indent, fence });
    await composer.getByText("Prose after the example:", { exact: false }).waitFor();
    await app.screenshot(label);
    results.push(await browser.evaluate(() => {
      const editor = document.querySelector('[data-testid="composer-editor"]')!;
      const text = editor.textContent ?? "";
      const [example, prose] = text.split("Prose after the example:");
      return { literalExample: example!.includes("<t3-thread://v2/"), proseChip: prose!.includes("Source thread for link"), exampleChip: example!.includes("Source thread for link") };
    }));
  }
  expect(results).toEqual([
    { literalExample: true, proseChip: true, exampleChip: false },
    { literalExample: true, proseChip: true, exampleChip: false },
    { literalExample: true, proseChip: true, exampleChip: false },
    { literalExample: false, proseChip: true, exampleChip: true },
  ]);
});
