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

test("Escape cancels custom model forms while keeping Settings open", WEB, async ({ t3, app, screen, browser }) => {
  const settled = () => browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {})));
    return null;
  });
  const afterEscapeSettled = async () => {
    await settled();
    if (!(await browser.evaluate(() => document.querySelector('[data-app-modal]') !== null))) {
      await screen.getByRole("heading", /What should we build in/).waitFor();
    }
    await settled();
  };
  const project = await t3.project("custom-model-demo");
  const thread = await t3.thread({ project, title: "Custom model settings", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/providers?instanceId=codex");
  const slug = screen.getByPlaceholder("gpt-6.7-codex-ultra-preview", { exact: true });
  await screen.getByRole("button", "Add custom model", { exact: true }).tap();
  await slug.fill("my-model");
  await settled();
  await app.screenshot("add-draft-before-escape");
  await slug.press("Escape");
  await afterEscapeSettled();
  await app.screenshot("add-after-escape");
  const addKeptSettings = await browser.evaluate(() => document.querySelector('[role="dialog"][aria-label="Settings"]') !== null || document.querySelector('[data-app-modal]') !== null);
  await t3.open("/settings/providers?instanceId=codex");
  await screen.getByRole("button", "Add custom model", { exact: true }).tap();
  await slug.fill("kept-model");
  await slug.press("Enter");
  await screen.getByRole("button", "Edit kept-model", { exact: true }).tap();
  const name = screen.getByRole("textbox", "Display name", { exact: true });
  await name.fill("Draft display name");
  await settled();
  await app.screenshot("edit-draft-before-escape");
  await name.press("Escape");
  await afterEscapeSettled();
  await app.screenshot("edit-after-escape");
  const editKeptSettings = await browser.evaluate(() => document.querySelector('[data-app-modal]') !== null);
  expect(addKeptSettings).toBe(true);
  expect(editKeptSettings).toBe(true);
  await expect(name).toBeHidden();
  await screen.getByRole("dialog", "Settings", { exact: true }).press("Escape");
  await afterEscapeSettled();
  await app.screenshot("second-escape-closes-settings");
  await expect(screen.getByRole("dialog", "Settings", { exact: true })).toBeHidden();
});
