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

// Replay the exact macOS Chromium event from the reported native IME run.
// This verifies the real app's handling; it does not create a native IME candidate window.
test("IME Escape preserves the theme editor and its unsaved name", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Create theme", { exact: true }).tap();
  const name = screen.getByRole("textbox", "Theme name", { exact: true });
  await name.fill("Aurora");
  await name.focus();
  await app.screenshot("before-ime-escape");
  await browser.evaluate(() => {
    const input = document.activeElement;
    if (!(input instanceof HTMLInputElement)) throw new Error("Theme name is not focused");
    input.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "" }));
    input.dispatchEvent(new CompositionEvent("compositionupdate", { bubbles: true, data: "かな" }));
    input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", code: "Escape", keyCode: 229, isComposing: true, bubbles: true, cancelable: true }));
    input.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "" }));
    return null;
  });
  await app.screenshot("after-ime-escape");
  await expect(name).toHaveValue("Aurora");
});
