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

test("Escape dismisses Cite before Find in thread", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "go", messages: ["go"], model: "default" });
  await t3.open(thread);
  const start = screen.getByText("Asks before it writes", { exact: true });
  await start.waitFor({ timeout: 120_000 });
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await start.tap();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").waitFor();
  const points = await browser.evaluate(() => {
    const items = [...document.querySelectorAll("li")];
    const first = items.find(el => el.textContent === "Asks before it writes");
    const last = items.find(el => el.textContent === "Streams a terminal result");
    if (!first || !last) throw new Error("Missing showcase list");
    const a = first.getBoundingClientRect();
    const b = last.getBoundingClientRect();
    return { x1: a.left + 1, y1: a.top + a.height / 2, x2: b.left + b.width - 1, y2: b.top + b.height / 2 };
  });
  await browser.mouse.move(points.x1, points.y1);
  await browser.mouse.down();
  await browser.mouse.move(points.x2, points.y2);
  await browser.mouse.up();
  await screen.getByRole("button", "Cite selection in composer").waitFor();
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("cite-and-find-visible");
  await browser.keyboard.press("Escape");
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("first-escape-keeps-find");
  const findAfterFirstEscape = await browser.evaluate(() => !!document.querySelector('[data-thread-find-bar]'));
  await expect(screen.getByRole("button", "Cite selection in composer")).not.toBeVisible();
  await browser.keyboard.press("Escape");
  await expect(screen.getByRole("searchbox", "Find in thread")).not.toBeVisible();
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("second-escape-closes-find");
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").waitFor();
  await browser.keyboard.press("Escape");
  await expect(screen.getByRole("searchbox", "Find in thread")).not.toBeVisible();
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot("find-only-escape-closes-find");
  await expect(findAfterFirstEscape).toBe(true);
});
