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

test("Wrapping selected code beside a literal @mention preserves the selection", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Code selection wrapping", messages: ["Hello"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await browser.evaluate(async () => {
    await navigator.clipboard.writeText("```\necho @prod next\n```");
    return null;
  });
  await browser.keyboard.press("ControlOrMeta+V");
  await browser.locator('[role="textbox"] pre').waitFor();
  await browser.evaluate(() => {
    const code = document.querySelector('[role="textbox"] pre code');
    if (!code) throw new Error("Pasted code block missing");
    const range = document.createRange();
    range.selectNodeContents(code);
    range.collapse(false);
    const selection = window.getSelection();
    selection?.removeAllRanges();
    selection?.addRange(range);
    return null;
  });
  await browser.keyboard.press("End");
  for (let i = 0; i < 5; i++) await browser.keyboard.press("Shift+ArrowLeft");
  const selected = await browser.evaluate(() => window.getSelection()?.toString());
  if (selected !== " next") throw new Error(`Expected selected suffix, got ${JSON.stringify(selected)}`);
  await app.screenshot("selected-code-suffix");
  await browser.keyboard.type("(");
  await app.screenshot("wrapped-code-suffix");
  await expect(browser.locator('[role="textbox"] pre code')).toHaveText("echo @prod( next)");
});
