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

test("Escape closes Find before dismissing the cited passage", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo");
  const thread = await t3.thread({ project, title: "Citation and Find", messages: ["Give me a short tour"], model: "showcase" });
  await t3.open(thread);
  await screen.getByText("This turn is a replay. It costs nothing, so send it again as often as you need.", { exact: true }).waitFor();
  await browser.evaluate(() => {
    const text = "This turn is a replay. It costs nothing, so send it again as often as you need.";
    const root = document.querySelector("[data-assistant-citation-source]")!;
    const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
    let node;
    while ((node = walker.nextNode())) {
      const start = node.textContent!.indexOf(text);
      if (start >= 0) {
        (node.parentElement as HTMLElement).scrollIntoView({ block: "center" });
        root.dispatchEvent(new KeyboardEvent("keydown", { key: "Shift", bubbles: true }));
        const range = document.createRange();
        range.setStart(node, start); range.setEnd(node, start + text.length);
        window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range);
        document.dispatchEvent(new Event("selectionchange"));
        return;
      }
    }
    throw new Error("Replay sentence missing");
  });
  await screen.getByRole("button", "Cite selection in composer").tap();
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByRole("textbox", "Message Citation and Find").press("Enter");
  const quote = browser.locator('[data-user-message-body] a[href*="assistant-citation="]');
  await quote.waitFor();
  await quote.tap();
  await browser.locator("[data-citation-highlighted]").waitFor();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").waitFor();
  await browser.keyboard.press("Escape");
  await browser.locator("[data-thread-find-bar]").waitFor({ state: "hidden" });
  const preserved = await browser.evaluate(() => !!document.querySelector("[data-citation-highlighted]"));
  await app.screenshot("first-escape-find-closed");
  expect(preserved).toBe(true);
  await browser.keyboard.press("Escape");
  const dismissed = await browser.evaluate(() => !document.querySelector("[data-citation-highlighted]"));
  await app.screenshot("second-escape-highlight-dismissed");
  expect(dismissed).toBe(true);
});
