import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "Workflow panels restore focus to the control that can reopen them",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const focusFailures: string[] = [];
    const checkFocus = async (name: string, check: () => Promise<unknown>) => {
      try { await check(); } catch { focusFailures.push(name); }
    };
    await browser.setViewport({ width: 1280, height: 800 });
    await t3.project("demo");
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const directory = path.join(T3_HOME, "workflows");
        yield* fs.makeDirectory(directory, { recursive: true });
        yield* fs.writeFileString(
          path.join(directory, "keyboard-report.ts"),
          `export default T3.workflow("keyboard-report", { version: 1, payload: Schema.Struct({}) },
          Effect.fn(function* () { yield* T3.subject("https://example.com/report"); yield* T3.title("Nightly report"); }));`,
        );
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
        yield* makeState(T3_HOME).cli(["workflow", "start", "keyboard-report", "--key", "one"]);
      }).pipe(Effect.scoped),
    );

    await t3.open("/workflows");
    const tab = screen.getByRole("button", "Nightly report", { exact: true });
    await tab.waitFor();
    const toggle = screen.getByRole("button", "Toggle right panel");
    await tab.focus();
    await browser.keyboard.press("ControlOrMeta+W");
    await checkFocus("panel toggle", () => expect(toggle).toBeFocused({ timeout: 1500 }));
    await app.screenshot("wide-toggle-focused");

    const runs = screen.getByRole("navigation", "Workflow runs");
    const row = runs.getByRole("button", /Nightly report/);
    await row.focus();
    await browser.keyboard.press("Enter");
    await tab.waitFor();
    await tab.focus();
    await browser.keyboard.press("ControlOrMeta+W");
    await checkFocus("run row", () => expect(row).toBeFocused({ timeout: 1500 }));
    await app.screenshot("run-row-focused");

    await row.tap();
    await tab.waitFor();
    await browser.setViewport({ width: 1280, height: 800 });
    await tab.focus();
    await browser.keyboard.press("ControlOrMeta+Alt+B");
    await checkFocus("toggle shortcut row", () => expect(row).toBeFocused({ timeout: 1500 }));
    await app.screenshot("toggle-shortcut-row-focused");
    await row.tap();
    await tab.waitFor();

    const subject = runs.getByRole("button", "example.com", { exact: true });
    const closePane = screen.getByRole("button", "Close the pane");
    for (const width of [1280, 1024]) {
      await browser.setViewport({ width, height: 800 });
      await subject.focus();
      await browser.keyboard.press("Enter");
      if (width === 1024) await subject.waitFor({ state: "hidden" });
      await closePane.focus();
      await browser.keyboard.press("Enter");
      await closePane.waitFor({ state: "hidden" });
      await checkFocus(`subject chip ${width}`, () => expect(subject).toBeFocused({ timeout: 1500 }));
      await app.screenshot(`subject-focused-${width}`);
    }

    await subject.tap();
    await closePane.focus();
    await browser.keyboard.press("ControlOrMeta+W");
    await closePane.waitFor({ state: "hidden" });
    await checkFocus("panel toggle", () => expect(toggle).toBeFocused({ timeout: 1500 }));

    await app.screenshot("both-panes-closed-toggle-focused");
    await browser.setViewport({ width: 650, height: 800 });
    await toggle.tap();
    await tab.focus();
    await browser.keyboard.press("ControlOrMeta+W");
    await tab.waitFor({ state: "hidden" });
    await checkFocus("panel toggle", () => expect(toggle).toBeFocused({ timeout: 1500 }));
    await app.screenshot("after-closing-in-narrow-layout");
    await expect(focusFailures).toEqual([]);
  },
);
