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

const SOCKET = `t3-ctrl-b-${process.pid}`;
const tmux = (...args: string[]) => runPromise(run("tmux", ["-L", SOCKET, ...args], {
  env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "" }, allowExit: [0, 1],
}));
const windows = async () => (await tmux("list-windows", "-F", "#{window_index}")).stdout.trim().split("\n").filter(Boolean).length;

test("Ctrl+B reaches focused tmux and toggles the sidebar outside the terminal", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Terminal shortcut demo", {
    "tmux.conf": "set -g status-right ''\nset -g default-command \"env PS1='demo$ ' bash --noprofile --norc\"\n",
  });
  const thread = await t3.thread({ project, title: "Ctrl+B terminal proof", messages: ["hello"] });
  const readReady = () => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${project}/ready`);
  }).pipe(Effect.orElseSucceed(() => "")));
  const sidebarState = () => browser.evaluate(() => document.querySelector('[data-slot="sidebar"][data-state]')?.getAttribute("data-state"));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("export PS1='demo$ '; echo ready > ready; clear");
    await browser.keyboard.press("Enter");
    return readReady();
  }, { timeout: 30000 }).toBe("ready\n");
  try {
    await terminal.focus();
    await browser.keyboard.type(`tmux -L ${SOCKET} -f tmux.conf new -s repro`);
    await browser.keyboard.press("Enter");
    await expect.poll(windows, { timeout: 15000 }).toBe(1);
    await tmux("set-option", "status-right", "");
    await app.screenshot("before-prefix");
    await terminal.focus();
    await browser.keyboard.press("Control+b");
    await browser.keyboard.type("c");
    await tmux("list-windows");
    await app.screenshot("ctrl-b-then-c");
    await expect.poll(windows, { timeout: 5000 }).toBe(2);
    await expect.poll(sidebarState).toBe("expanded");
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    await screen.getByRole("button", "Toggle main sidebar").focus();
    await browser.keyboard.press("Control+b");
    await expect.poll(sidebarState).toBe("collapsed");
    await app.screenshot("outside-terminal-sidebar-hidden");
    await browser.keyboard.press("Control+b");
    await expect.poll(sidebarState).toBe("expanded");
    await app.screenshot("outside-terminal-sidebar-restored");
  } finally { await tmux("kill-server"); }
});
