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

test("One undo removes a citation after saving its empty comment unchanged", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo");
  const thread = await t3.thread({ project, title: "Citation undo", model: "showcase", messages: ["hello"] });
  await t3.open(thread);
  await browser.locator('[data-assistant-citation-source] p').filter({ hasText: "This turn is a replay" }).waitFor({ timeout: 120_000 });
  await browser.evaluate(() => {
    const paragraphs = Array.from(document.querySelectorAll('[data-assistant-citation-source] p'));
    const paragraph = paragraphs.find((p) => p.textContent?.includes("This turn is a replay")) ?? paragraphs.at(-1);
    if (!paragraph) throw new Error("Replay paragraph missing");
    paragraph.scrollIntoView({ block: "center" });
    const range = document.createRange();
    range.selectNodeContents(paragraph);
    const selection = window.getSelection()!;
    selection.removeAllRanges();
    selection.addRange(range);
    document.dispatchEvent(new Event("selectionchange"));
    return null;
  });
  await screen.getByRole("button", "Cite selection in composer").tap();
  await screen.getByRole("textbox", "Comment on selected text").focus();
  await browser.keyboard.press("Enter");
  await app.screenshot("citation-saved-empty-comment");
  await browser.keyboard.press("Control+z");
  await app.screenshot("after-one-undo");
  await expect(browser.locator('[data-composer-citation-chip="true"]')).toHaveCount(0);
});
