import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Escape clears Registry search and preserves Add provider", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("registry-demo");
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Add provider", { exact: true }).first().tap();
  await screen.getByRole("button", "Show more", { exact: true }).tap();
  const search = screen.getByRole("searchbox", "Search ACP Registry");
  await search.fill("cline");
  await screen.getByText("Cline", { exact: true }).waitFor();
  await app.screenshot("populated-registry-search");
  await browser.keyboard.press("Escape");
  await app.screenshot("first-escape");
  await expect.poll(() => browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[aria-label="Search ACP Registry"]');
    return !!input && input.value === "" && document.activeElement === input;
  })).toBe(true);
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true, cancelable: true }));
  });
  await expect(search).toBeVisible();
  await search.fill("cline");
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", isComposing: true, bubbles: true, cancelable: true }));
  });
  await expect.poll(() => browser.evaluate(() => (document.activeElement as HTMLInputElement)?.value)).toBe("cline");
  await app.screenshot("ime-escape-preserves-query");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  await expect(search).not.toBeVisible();
  await app.screenshot("separate-empty-escape-closes-add-provider");
});
