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

test("Escape closes the media preview before stopping a running thread", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Media preview");
  await t3.open();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await screen.getByRole("option", "Multi turn", { exact: false }).waitFor();
  await browser.keyboard.press("Escape");
  const thread = await t3.thread({ project, title: "Image description", messages: ["Start"] });
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${T3_HOME}/userdata/keybindings.json`, '[{"key":"escape","command":"thread.stop"}]\n')));
  await t3.open(thread);
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await browser.keyboard.type("Long stream");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(async (selector) => {
    const canvas = document.createElement("canvas"); canvas.width = 800; canvas.height = 500;
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#17394f"; ctx.fillRect(0, 0, 800, 500);
    ctx.fillStyle = "#f5cb73"; ctx.fillRect(90, 110, 620, 280);
    ctx.fillStyle = "#17394f"; ctx.font = "36px sans-serif"; ctx.fillText("Media preview · Escape", 180, 260);
    const blob = await new Promise<Blob>(resolve => canvas.toBlob(b => resolve(b!), "image/png"));
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    const files = new DataTransfer(); files.items.add(new File([blob], "sample.png", { type: "image/png" }));
    picker.files = files.files; picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, input);
  await screen.getByRole("button", "Preview sample.png").waitFor();
  const composer = screen.getByTestId("composer-editor");
  await composer.fill("Describe this image at length");
  await composer.press("Enter");
  const stop = screen.getByRole("button", "Stop generation");
  await stop.waitFor();
  const opener = screen.getByRole("button", "Preview sample.png");
  await opener.tap();
  await screen.getByRole("button", "Close image preview").waitFor();
  await app.screenshot("preview-before-escape");
  await browser.keyboard.press("Escape");
  try {
    await expect(screen.getByRole("button", "Close image preview")).toBeHidden();
    await expect(stop).toBeVisible();
    await expect(opener).toBeFocused();
  } finally {
    await app.screenshot("first-escape");
  }
  await browser.keyboard.press("Escape");
  await expect(stop).toBeHidden();
  await app.screenshot("second-escape-stops-thread");
});
