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

test("A local clear command with unavailable context names its Enter action during a running turn", WEB, async ({ t3, app, browser, screen }) => {
  await browser.addInitScript(() => {
    const postMessage = Worker.prototype.postMessage;
    const pending: Array<() => void> = [];
    (window as any).releaseImageCompression = () => pending.splice(0).forEach(resume => resume());
    Worker.prototype.postMessage = function(message, options) {
      if (message?.task?.kind === "fit") {
        pending.push(() => Reflect.apply(postMessage, this, [message, options]));
        return;
      }
      return Reflect.apply(postMessage, this, [message, options]);
    };
  });
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("Local command demo");
  const thread = await t3.thread({ project, title: "Local commands", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate(async () => {
    await (window as any).t3dev.replay("bench-stream");
    return null;
  });
  await screen.getByRole("button", "Stop generation", { exact: true }).waitFor();
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await browser.evaluate(() => {
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", "[Reply](t3-context://v1/response/response_gone) ");
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  });
  await composer.getByText("Reply", { exact: true }).waitFor();
  await composer.pressSequentially("/clear ");
  await screen.getByRole("button", /^(Submit|Steer|Queue) message$/).hover();
  await screen.getByText(/^(Click to steer,|Submit message$)/).waitFor();
  await browser.evaluate(() => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    return null;
  });
  await app.screenshot("local-clear-draft-during-running-turn");
  const action = await browser.evaluate(() => [...document.querySelectorAll('button')].map(b => b.getAttribute('aria-label')).find(label => /^(Submit|Steer|Queue) message$/.test(label ?? "")));
  await browser.keyboard.press("Enter");
  await screen.getByText("Your next message starts a fresh session", { exact: false }).waitFor();
  await app.screenshot("enter-runs-clear-locally");
  await composer.fill("/clear ");
  await pasteWideScreenshot(browser);
  await screen.getByRole("button", /^(Submit|Steer|Queue) message$/).hover();
  await screen.getByText(/^(Click to steer,|Submit message$)/).waitFor();
  await browser.evaluate(() => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    return null;
  });
  const imageAction = await browser.evaluate(() => [...document.querySelectorAll('button')].map(b => b.getAttribute('aria-label')).find(label => /^(Submit|Steer|Queue) message$/.test(label ?? "")));
  await app.screenshot("clear-with-image-still-compressing");
  await composer.press("Enter");
  await app.screenshot("enter-waits-for-compression");
  await browser.evaluate(() => { (window as any).releaseImageCompression(); return null; });
  await screen.getByRole("button", "Edit queued message").waitFor();
  await screen.getByRole("button", "Send now", { exact: true }).waitFor();
  await app.screenshot("clear-sent-as-message-with-image");
  expect([action, imageAction], "The button names what Enter does with unavailable context and with a compressing image").toEqual(["Submit message", "Steer message"]);
});
