import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Comma-only keybindings report invalid configuration", WEB, async ({ t3, app, screen }) => {
  await t3.project("keybindings-demo");
  await t3.open("/settings/keybindings");
  await screen.getByLabel("Search keybindings").waitFor();
  const write = (text: string) => runPromise(Effect.flatMap(FileSystem.FileSystem,
    fs => fs.writeFileString(`${T3_HOME}/userdata/keybindings.json`, text)));
  const warning = screen.getByText("Invalid keybindings configuration", { exact: true });
  try {
    // Control: prove the real watcher and notification path are connected.
    await write("[{");
    await warning.waitFor();
    await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: Ctrl+K", { exact: true }).waitFor();
    await app.screenshot("malformed-control");
    await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
    await warning.waitFor({ state: "hidden" });
    await write('[ { "key": "f8", "command": "commandPalette.toggle" }, ]');
    await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: F8", { exact: true }).waitFor();
    await write("[,]");
    await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: Ctrl+K", { exact: true }).waitFor();
    try {
      await expect(warning).toBeVisible();
    } finally {
      await app.screenshot("comma-only-array");
    }
    await screen.getByRole("button", "Dismiss notification", { exact: true }).tap();
    await warning.waitFor({ state: "hidden" });
    await write('[ { "key": "f8", "command": "commandPalette.toggle" }, ]');
    await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: F8", { exact: true }).waitFor();
    await write("[ /* note */ , ]");
    await screen.getByRole("button", "Edit shortcut for Command Palette: Toggle: Ctrl+K", { exact: true }).waitFor();
    try {
      await expect(warning).toBeVisible();
    } finally {
      await app.screenshot("commented-comma-only-array");
    }
  } finally {
    await write("[]");
  }
});
