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

test("Typing after following a citation source keeps the citation and comment", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("citation-demo");
  const thread = await t3.thread({ project, title: "Citation draft", model: "showcase", messages: ["show me the demo"] });
  await t3.open(thread);
  const bullet = screen.getByText("Asks before it writes", { exact: false });
  await bullet.tap();
  await browser.evaluate(() => {
    const item = [...document.querySelectorAll("li")].find(el => el.textContent?.startsWith("Asks before it writes"));
    if (!item) throw new Error("Missing showcase bullet");
    const range = document.createRange();
    range.selectNodeContents(item);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    document.dispatchEvent(new Event("selectionchange"));
    return null;
  });
  await screen.getByRole("button", "Cite selection in composer").tap();
  const comment = screen.getByPlaceholder("Add an optional comment...");
  await comment.fill("note");
  await comment.press("Enter");
  await browser.keyboard.type("Please look at ");
  await app.screenshot("draft-before-link");
  await screen.getByRole("link", "View cited assistant text: note").tap();
  await app.screenshot("after-source-link");
  await browser.keyboard.type(" this");
  await app.screenshot("draft-after-typing");
  await expect(screen.getByRole("link", "View cited assistant text: note")).toBeVisible();
  await expect(screen.getByRole("textbox")).toContainText("Please look at");
  await expect(screen.getByRole("textbox")).toContainText("this");
});
