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

test("Copying prose at either inline-code boundary adds no backticks", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Inline code copy", messages: ["I added `clamp` next to `sum` and the tests pass."] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent I added/).tap();
  const results: string[] = [];
  for (const side of ["before", "after"]) {
    await browser.evaluate((side) => {
      const code = [...document.querySelectorAll("p code")].find(el => el.textContent === "clamp");
      if (!code?.firstChild || !code.previousSibling || !code.nextSibling) throw new Error("Rendered clamp paragraph missing");
      const range = document.createRange();
      if (side === "before") {
        range.setStart(code.previousSibling, 0);
        range.setEnd(code.firstChild, 0);
      } else {
        range.setStart(code.firstChild, 5);
        range.setEnd(code.nextSibling, code.nextSibling.textContent?.length ?? 0);
      }
      const selection = window.getSelection();
      selection?.removeAllRanges();
      selection?.addRange(range);
      return selection?.toString();
    }, side);
    await browser.keyboard.press("ControlOrMeta+C");
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+A");
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot(side === "before" ? "prose-before-code-pasted" : "prose-after-code-pasted");
    results.push(await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent ?? ""));
  }
  await expect(results).toEqual(["I added", "next to"]);
});
