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

test("Copied chat links preserve literal character references and labels", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("link-round-trip");
  const thread = await t3.thread({ project, title: "Copy link round trip", messages: ["Ready"], model: "default" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  const results = [];
  for (const label of ["Guide", "https://example.com/?q=&amp;copy;"]) {
    await composer.fill(`See [${label}](https://example.com/?q=&amp;copy;) now`);
    await browser.keyboard.press("Enter");
    await expect(screen.getByRole("button", "Submit message")).toBeVisible();
    await browser.evaluate(() => {
      const paragraphs = [...document.querySelectorAll("[data-user-message-body] p")];
      const paragraph = paragraphs.filter(p => p.querySelector('a[href="https://example.com/?q=&copy;"]')).at(-1);
      if (!paragraph) throw new Error("No rendered source link");
      const range = document.createRange();
      paragraph.scrollIntoView({ block: "center" });
      range.selectNodeContents(paragraph);
      window.getSelection()?.removeAllRanges();
      window.getSelection()?.addRange(range);
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+C");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot(label === "Guide" ? "labelled-pasted" : "url-labelled-pasted");
    await browser.keyboard.press("Enter");
    await expect(screen.getByRole("button", "Submit message")).toBeVisible();
    await browser.evaluate(() => {
      [...document.querySelectorAll("[data-user-message-body] p")].at(-1)?.scrollIntoView({ block: "center" });
      return null;
    });
    await app.screenshot(label === "Guide" ? "labelled-sent" : "url-labelled-sent");
    results.push(await browser.evaluate(() => {
      const paragraph = [...document.querySelectorAll("[data-user-message-body] p")].at(-1);
      const link = paragraph?.querySelector("a");
      return { href: link?.getAttribute("href"), label: link?.textContent, text: paragraph?.textContent };
    }));
  }
  expect(results).toEqual([
    { href: "https://example.com/?q=&copy;", label: "Guide", text: "See Guide now" },
    { href: "https://example.com/?q=&copy;", label: "https://example.com/?q=&copy;", text: "See https://example.com/?q=&copy; now" },
  ]);
});
