import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Escape clears the provider model filter before closing Settings", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("model-filter-demo");
  const thread = await t3.thread({ project, title: "Model filter demo", messages: ["Start"] });
  await t3.open(thread);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { providerInstances: { codex: { driver: "codex", enabled: true, config: { binaryPath: "codex" } } } } });
  }).pipe(Effect.scoped));
  await t3.open("/settings/providers?instanceId=codex");
  const filter = screen.getByPlaceholder("Filter models", { exact: true });
  await filter.fill("gpt-6");
  await browser.evaluate(() => {
    document.querySelector('input[placeholder="Filter models"]')?.scrollIntoView({ block: "center" });
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    return null;
  });
  await app.screenshot("populated-filter");
  await browser.keyboard.press("Escape");
  try {
    await expect(filter).toHaveValue("");
    await expect(filter).toBeVisible();
    await expect(filter).toBeFocused();
  } finally {
    await browser.evaluate(() => {
      for (const animation of document.getAnimations()) {
        if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
      }
      return null;
    });
    await app.screenshot("after-first-escape");
  }
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true, cancelable: true }));
    return null;
  });
  await app.screenshot("held-escape-repeat");
  await expect(filter).toBeVisible();
  await filter.fill("gpt-6");
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", isComposing: true, bubbles: true, cancelable: true }));
    return null;
  });
  await app.screenshot("ime-escape");
  await expect(filter).toHaveValue("gpt-6");
  await expect(filter).toBeFocused();
  await browser.keyboard.press("Escape");
  await expect(filter).toHaveValue("");
  await browser.keyboard.press("Escape");
  await expect(filter).not.toBeVisible();
  await browser.evaluate(() => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    return null;
  });
  await app.screenshot("fresh-escape-closes-settings");
});
