import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Hosted thread links preserve surrounding URLs and Markdown", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("link-demo");
  const source = await t3.thread({ project, title: "Readable source", messages: ["Source material"] });
  const destination = await t3.thread({ project, title: "Paste destination", messages: ["Check pasted links"] });
  await t3.open(destination);
  const environment = await browser.evaluate(async () => (await (await fetch("/.well-known/t3/environment")).json()).environmentId);
  const hosted = `https://app.t3.codes/threads/${encodeURIComponent(environment)}/${encodeURIComponent(source.threadId)}`;
  const editor = screen.getByTestId("composer-editor");
  const chips = screen.getByRole("link", "Thread, Readable source");
  const paste = async (text: string) => {
    await editor.tap();
    await browser.keyboard.press("ControlOrMeta+A");
    await browser.keyboard.press("Backspace");
    await browser.evaluate(async (value: string) => { await navigator.clipboard.writeText(value); }, text);
    await browser.keyboard.press("ControlOrMeta+V");
  };
  await paste(hosted);
  await expect(chips).toHaveCount(1);
  await app.screenshot("standalone-control");
  await paste(`[Example](${hosted})`);
  await expect(chips).toHaveCount(1);
  await app.screenshot("labeled-control");
  for (const [label, text] of [
    ["outer-url", `https://example.com/?next=${hosted}`],
    ["outer-markdown-destination", `[Example](https://example.com/?next=${hosted})`],
    ["outer-markdown-label", `[ ${hosted} ](https://example.com)`],
  ]) {
    await paste(text);
    await editor.press("ArrowRight");
    await app.screenshot(label);
    await expect.soft(chips).toHaveCount(0);
  }
});
