/// <reference lib="dom" />
import { copyFileSync, chmodSync, existsSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const kept = "a".repeat(127);
test("Closing a long command keeps complete characters", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({colorScheme:"dark"});
  const project = await t3.project("demo");
  const executable = `${project}/${kept}😀-sleep`;
  copyFileSync("/bin/sleep", executable);
  chmodSync(executable, 0o755);
  execFileSync("codesign", ["-f", "-s", "-", executable]);
  const thread = await t3.thread({project, title:"Long command label", messages:["hello"]});
  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("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return existsSync(`${project}/shell-ready`);
  }, {timeout:30000}).toBe(true);
  await terminal.focus();
  await browser.keyboard.type("clear; ./a* 300");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", kept, {exact:true}).waitFor({timeout:30000}).catch(() => {});
  await screen.getByRole("button", "Close Terminal (⌘W)", {exact:true}).tap();
  await screen.getByRole("alertdialog").waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    return null;
  });
  await app.screenshot("close-long-command");
  const text = await browser.evaluate(() => document.querySelector('[role="alertdialog"]')?.textContent ?? "");
  expect(text).toContain(`Close terminal "${kept}"?`);
});
