/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("IME typing preserves composer focus with a letter palette shortcut", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("IME demo");
  const thread = await t3.thread({ project, title: "New thread", messages: ["Hello"], model: "default" });
  await writeFile(`${T3_HOME}/userdata/keybindings.json`, JSON.stringify([{key:"k",command:"commandPalette.toggle"}]));
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  execFileSync("ibus", ["engine", "xkb:us::eng"]);
  await browser.keyboard.press("k");
  await screen.getByRole("dialog").waitFor();
  await browser.keyboard.press("Escape");
  await composer.tap();
  await browser.evaluate(() => {
    const events: unknown[] = [];
    (window as any).imeEvents = events;
    for (const type of ["compositionstart", "compositionend", "keydown"]) {
      document.addEventListener(type, (event) => {
        const e = event as KeyboardEvent & CompositionEvent;
        queueMicrotask(() => events.push({type:e.type,key:e.key,code:e.code,keyCode:e.keyCode,isComposing:e.isComposing,prevented:e.defaultPrevented,data:e.data}));
      });
    }
  });
  try { execFileSync("ibus", ["engine", "mozc-jp"]); } catch {}
  if (execFileSync("ibus", ["engine"]).toString().trim() !== "mozc-jp") throw new Error("Mozc did not activate");
  const windows = execFileSync("xdotool", ["search", "--onlyvisible", "--name", "New thread"]).toString().trim().split("\n");
  execFileSync("xdotool", ["windowfocus", "--sync", windows.at(-1)!]);
  execFileSync("xdotool", ["key", "Hiragana"]);
  execFileSync("xdotool", ["type", "--clearmodifiers", "--delay", "350", "nika"]);
  await app.screenshot("ime-nika-composer");
  const state = await browser.evaluate(() => JSON.parse(JSON.stringify({
    events:(window as any).imeEvents,
    palette:!!document.querySelector('[role="dialog"]'),
    focused:document.activeElement?.getAttribute("data-testid"),
    text:document.querySelector('[data-testid="composer-editor"]')?.textContent,
  })));
  console.log(JSON.stringify(state));
  expect(state.events.some((e:any) => e.code === "KeyK" && e.keyCode === 229 && e.isComposing)).toBe(true);
  expect(state.palette).toBe(false);
  expect(state.focused).toBe("composer-editor");
  execFileSync("ibus", ["engine", "xkb:us::eng"]);
});
