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

// Run headed under an isolated X display. XTEST supplies real trusted browser events.
const x = (program: string, ...args: string[]) => execFileSync(program, args, { encoding: "utf8" });
const layout = (name: string) => x("setxkbmap", name);
const chord = (key: string) => {
  const windows = x("xdotool", "search", "--onlyvisible", "--class", "chromium").trim().split("\n");
  x("xdotool", "windowfocus", windows[0]!);
  x("xdotool", "key", "--clearmodifiers", `ctrl+alt+${key}`);
};

test("Alt shortcut recorded on Russian KeyB works after switching to English", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("shortcut-demo");
  const thread = await t3.thread({ project, title: "Keyboard layout demo", messages: ["Start"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open("/settings/keybindings");
  await screen.getByLabel("Search keybindings").fill("Command Palette");
  await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: Ctrl+K", { exact: true }).tap();
  const recorder = screen.getByRole("textbox", "Keybinding for Command Palette: Toggle", { exact: true });
  await recorder.focus();
  await browser.evaluate(() => {
    document.addEventListener("keydown", (e) => {
      if (e.code === "KeyB") document.documentElement.dataset.proofKey = JSON.stringify({key:e.key,code:e.code,ctrl:e.ctrlKey,alt:e.altKey,trusted:e.isTrusted});
    }, true);
    return null;
  });
  layout("ru");
  chord("Cyrillic_i");
  await browser.locator('html[data-proof-key]').waitFor({ state: "attached" });
  console.log("Russian input:", await browser.evaluate(() => document.documentElement.dataset.proofKey));
  await recorder.press("Tab");
  await app.screenshot("recorded-shortcut-and-conflict");
  const warning = await screen.getByLabel("Conflicts with Right Panel: Toggle.", { exact: true }).isVisible();
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByRole("button", /^Edit shortcut for Command Palette: Toggle: Ctrl\+Alt\+/).waitFor();
  const saved = readFileSync(`${T3_HOME}/userdata/keybindings.json`, "utf8");
  console.log("Saved bindings:", saved);
  await app.screenshot("saved-shortcut");
  await t3.open(thread);
  await screen.getByText("Start", { exact: true }).waitFor({ timeout: 30000 });
  layout("us");
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); return null; });
  chord("b");
  try {
    await expect(screen.getByRole("dialog", "Command palette")).toBeVisible();
    expect(warning).toBe(true);
    expect(JSON.parse(saved).some((binding: {key:string;command:string}) => binding.command === "commandPalette.toggle" && binding.key === "mod+alt+b")).toBe(true);
  } finally {
    await app.screenshot("english-shortcut-result");
    layout("us");
  }
});
