import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { test, WEB } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Option letters record, save and retain layout characters", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => Object.defineProperty(navigator, "platform", { configurable:true, get: () => "MacIntel" }));
  await t3.project("Shortcut demo");
  await t3.open("/settings/keybindings");
  await screen.getByRole("button", "Add keybinding").tap();
  await screen.getByRole("combobox").last().tap();
  await screen.getByRole("option", "Command Palette: Toggle", {exact:false}).tap();
  const field = browser.locator("input[data-keybinding-capture]").last();
  const values: Record<string,string> = {};
  const cases = [
    ["polish-altgr-a", "ą", "KeyA", "mod+alt+ą", "Win32"],
    ["dvorak-command-l", "l", "KeyP", "mod+l"],
    ["us-option-digit", "¡", "Digit1", "mod+alt+1"],
    ["dvorak-option-l", "¬", "KeyP", "mod+alt+¬"],
    ["azerty-option-a", "æ", "KeyQ", "mod+alt+æ"],
    ["us-option-d", "∂", "KeyD", "mod+alt+d"],
    ["us-option-l", "¬", "KeyL", "mod+alt+l"],
    ["us-option-p", "π", "KeyP", "mod+alt+p"],
  ];
  for (const [label,key,code,,platform = "MacIntel"] of cases) {
    await browser.evaluate((platform) => { Object.defineProperty(navigator, "platform", {configurable:true, get: () => platform}); return null; }, platform);
    await field.tap();
    await browser.evaluate(({key,code,platform,label}) => {
      const target = document.activeElement!;
      const metaKey = platform === "MacIntel";
      const ctrlKey = !metaKey;
      const altKey = label !== "dvorak-command-l";
      for (const event of [
        {key:"Meta",code:"MetaLeft",metaKey:true},
        {key:"Alt",code:"AltLeft",metaKey:true,altKey:true},
        {key,code,metaKey,ctrlKey,altKey},
      ]) target.dispatchEvent(new KeyboardEvent("keydown", { ...event, bubbles:true, cancelable:true }));
      return null;
    }, {key,code,platform,label});
    values[label] = await field.inputValue();
    await app.screenshot(label);
  }
  await screen.getByRole("button", "Save", {exact:true}).tap();
  await screen.getByRole("button", "Add keybinding").tap();
  await screen.getByRole("button", "Cancel new keybinding").tap();
  await app.screenshot("saved-shortcut-pill");
  await browser.reload();
  await screen.getByRole("button", "Add keybinding").tap();
  await screen.getByRole("button", "Cancel new keybinding").tap();
  await app.screenshot("persisted-after-reload");
  const json = await readFile(`${T3_HOME}/userdata/keybindings.json`, "utf8");
  await writeFile(`${tmpdir()}/factory-issue-38513-evidence-3/${values["us-option-p"] === "mod+alt+p" ? "after" : "before"}-keybindings.json`, json);
  await writeFile(`${tmpdir()}/factory-issue-38513-evidence-3/${values["us-option-p"] === "mod+alt+p" ? "after" : "before"}-recordings.json`, JSON.stringify(values, null, 2));
  for (const [label,,,expected] of cases) await expect(values[label]).toBe(expected);
  await expect(json).toContain('mod+alt+p');
});
