/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Short RGB terminal background survives a full browser reload", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "light" });
  const project = await t3.project("colors");
  const thread = await t3.thread({ project, title: "Terminal colors", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.waitFor();
  const pixel = () => browser.evaluate(() => {
    const canvas = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas");
    if (!canvas) return [];
    return [...canvas.getContext("2d")!.getImageData(canvas.width - 20, Math.floor(canvas.height / 2), 1, 1).data];
  });
  // Repeat only until the shell is ready to accept input, then leave a clean synthetic screen.
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type(String.raw`export PS1=''; clear; printf '\033]11;rgb:44/55/66\007sample\n'`);
    await browser.keyboard.press("Enter");
    return pixel();
  }, { timeout: 30_000 }).toEqual([68, 85, 102, 255]);
  await app.screenshot("live-short-rgb-background");
  await browser.reload();
  await terminal.waitFor();
  await browser.locator('[aria-label="Terminal input"]').focus();
  await app.screenshot("reattached-short-rgb-background");
  await expect.poll(pixel).toEqual([68, 85, 102, 255]);
});
