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 popup blocks panel shortcuts until Escape", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("workflow-shortcuts");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    for (const [name, title] of [["panel-demo", "Nightly check"], ["audit-demo", "Audit check"]]) {
      yield* fs.writeFileString(`${T3_HOME}/workflows/${name}.ts`,
        `export default T3.workflow("${name}", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.title("${title}"); }));`);
    }
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    for (const name of ["audit-demo", "panel-demo"]) {
      yield* makeState(T3_HOME).cli(["workflow", "start", name, "--key", "one"]);
    }
  }).pipe(Effect.scoped));
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open("/workflows");
  const runs = screen.getByRole("navigation", "Workflow runs");
  const row = runs.getByRole("button", /Nightly check/);
  await row.tap();
  const panel = browser.locator('[data-workspace-area="panel"]');
  await panel.waitFor();
  const workflow = screen.getByRole("combobox", "Workflow", { exact: true });
  const option = screen.getByRole("option", "All workflows", { exact: true });
  await workflow.tap();
  await option.waitFor();
  await browser.keyboard.press("ControlOrMeta+Alt+b");
  await app.screenshot("toggle-with-workflow-popup-open");
  // Restore the same starting state before the second shortcut on either commit.
  await browser.keyboard.press("Escape");
  await row.tap();
  await panel.waitFor();
  await workflow.tap();
  await option.waitFor();
  await browser.keyboard.press("ControlOrMeta+w");
  await app.screenshot("close-with-workflow-popup-open");
  await expect(panel).toBeVisible();
  await expect(option).toBeVisible();
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("ControlOrMeta+w");
  await expect(panel).toHaveCount(0);
  await browser.keyboard.press("ControlOrMeta+Alt+b");
  await expect(panel).toBeVisible();
  await app.screenshot("shortcuts-work-after-popup-dismissed");
});
