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

test("Copying punctuation immediately before a link preserves the rendered link", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("copy-roundtrip");
  const threads = [];
  for (const [label, source, rendered] of [
    ["exclamation", String.raw`Wow\![the docs](https://x.com/docs)`, "Wow!the docs"],
    ["backslash-exclamation", String.raw`a\\\![the docs](https://x.com/docs)`, String.raw`a\!the docs`],
  ]) {
    const thread = await t3.thread({ project, title: label, messages: [source] });
    threads.push({ thread, label, rendered });
  }
  const results = [];
  for (const { thread, label, rendered } of threads) {
    await t3.open(thread);
    await screen.getByRole("button", /^Agent /).first().tap();
    await screen.getByRole("link", "the docs", { exact: true }).waitFor();
    await browser.evaluate(() => {
      const link = [...document.querySelectorAll('a')].find(a => a.textContent === 'the docs');
      const paragraph = link?.closest('p');
      if (!paragraph) throw new Error('Original paragraph missing');
      const range = document.createRange();
      range.selectNodeContents(paragraph);
      window.getSelection()?.removeAllRanges();
      window.getSelection()?.addRange(range);
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+C");
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot(`${label}-pasted`);
    await browser.keyboard.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: true }).waitFor();
    await app.screenshot(`${label}-sent`);
    results.push(await browser.evaluate(() => {
      const paragraphs = [...document.querySelectorAll('p')].filter(p => p.textContent?.startsWith('Wow') || p.textContent?.startsWith('a\\'));
      const p = paragraphs.at(-1);
      return { text: p?.textContent ?? null, href: p?.querySelector('a')?.getAttribute('href') ?? null };
    }));
    results[results.length - 1].expected = rendered;
  }
  for (const result of results) {
    expect(result.text).toBe(result.expected);
    expect(result.href).toBe("https://x.com/docs");
  }
});
