import { readFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Saved Ctrl+Space toggles the terminal, including after reload", WEB, async ({ t3, app, screen, browser }) => {
  const stableCapture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 10; attempt++) {
      await delay(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const project = await t3.project("shortcut-demo");
  await t3.thread({ project, title: "Space shortcut proof", messages: ["Hello"] });
  await t3.open();
  await screen.getByRole("button", /^Space shortcut proof,/).press("Enter", { timeout: 120_000 });
  const threadUrl = await browser.evaluate(() => location.pathname);
  await app.open("/settings/keybindings");
  await screen.getByRole("searchbox", "Search keybindings").fill("Terminal: Toggle");
  await screen.getByRole("button", /^Edit shortcut for Terminal: Toggle:/).tap();
  await browser.keyboard.press("Control+Space");
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await app.open(threadUrl);
  await screen.getByText("first fixture turn complete", { exact: true }).tap();
  await screen.getByRole("textbox").first().tap();
  await browser.keyboard.press("Control+Space");
  await expect.soft(browser.locator("[data-thread-terminal-drawer]")).toBeVisible();
  await stableCapture("space-pressed-before-reload");
  await browser.keyboard.press("Control+Space");
  await expect(browser.locator("[data-thread-terminal-drawer]")).toBeHidden();
  await browser.reload();
  await screen.getByText("first fixture turn complete", { exact: true }).tap();
  await screen.getByRole("textbox").first().tap();
  await browser.keyboard.press("Control+Space");
  await expect.soft(browser.locator("[data-thread-terminal-drawer]")).toBeVisible();
  await stableCapture("space-pressed-after-reload");
  await browser.keyboard.press("Control+Space");
  await expect(browser.locator("[data-thread-terminal-drawer]")).toBeHidden();
  await app.open("/settings/keybindings");
  await screen.getByRole("searchbox", "Search keybindings").fill("Terminal: Toggle");
  await stableCapture("saved-shortcut-after-reload");
  await expect.soft(screen.getByRole("button", "Edit shortcut for Terminal: Toggle: Ctrl+Space", { exact: true })).toBeVisible();
});
