/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Workflow tab menu keeps its run open during panel shortcuts", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${T3_HOME}/userdata/keybindings.json`, JSON.stringify([{ key: "alt+w", command: "rightPanel.close" }]));
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    yield* client["workflows.saveDefinition"]({ name: "demo.ts", source: `T3.workflow("my-workflow", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.title("Repro run"); return "Done"; }));` });
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli(["workflow", "start", "my-workflow", "--key", "demo", "--json"]));
  const { run } = JSON.parse(started.stdout);
  const results: boolean[] = [];
  for (const [label, shortcut] of [["close", "Alt+w"], ["toggle", "Control+Alt+b"]]) {
    await t3.open(`/workflows?run=${run.runId}`);
    await screen.getByRole("heading", "Repro run", { exact: true }).waitFor();
    await browser.evaluate(() => {
      const tab = document.querySelector('[data-active-tab="true"]');
      if (!tab) throw new Error("Workflow tab missing");
      const box = tab.getBoundingClientRect();
      tab.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 }));
      return null;
    });
    await screen.getByRole("menuitem", "Close", { exact: true }).waitFor();
    const focused = await browser.evaluate(() => !!document.activeElement?.closest('[role="menu"]'));
    if (!focused) throw new Error("Context menu did not receive focus");
    await app.screenshot(`${label}-menu-before-shortcut`);
    await browser.keyboard.press(shortcut);
    await app.screenshot(`${label}-menu-after-shortcut`);
    results.push(await browser.evaluate(() => !!document.querySelector('h2') && [...document.querySelectorAll('h2')].some(el => el.textContent === "Repro run")));
    await browser.keyboard.press("Escape");
  }
  expect(results).toEqual([true, true]);
});
