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

test("IME Escape preserves the painted citation highlight", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({project, title: "Citation Escape", messages: ["Hello, show me something"], model: "showcase"});
  await t3.open(thread);
  const sentence = screen.getByText("I added clamp next to sum and the tests pass.", {exact: true});
  await sentence.waitFor();
  await browser.evaluate(() => {
    const p = [...document.querySelectorAll("[data-assistant-citation-source] p")].find(p => p.textContent === "I added clamp next to sum and the tests pass.");
    if (!p) throw new Error("Missing citation sentence");
    p.dispatchEvent(new PointerEvent("pointerdown", {bubbles:true, isPrimary:true, button:0}));
    const range = document.createRange(); range.selectNodeContents(p);
    window.getSelection()?.removeAllRanges(); window.getSelection()?.addRange(range);
    document.dispatchEvent(new Event("selectionchange"));
    p.dispatchEvent(new PointerEvent("pointerup", {bubbles:true, isPrimary:true, button:0}));
    p.dispatchEvent(new MouseEvent("mouseup", {bubbles:true, button:0, detail:3}));
  });
  await screen.getByRole("button", "Cite selection in composer", {exact:true}).tap();
  await screen.getByRole("button", "Save", {exact:true}).tap();
  const chip = screen.getByRole("link", /^View cited assistant text:/);
  const highlight = browser.locator('[data-citation-highlighted="true"]');
  const reveal = async () => {
    await chip.tap();
    await browser.evaluate(() => {
      const composer = document.querySelector<HTMLElement>('[role="textbox"][contenteditable="true"]');
      if (!composer) throw new Error("Missing composer");
      composer.focus();
      const caret = document.createRange(); caret.selectNodeContents(composer); caret.collapse(false);
      window.getSelection()?.removeAllRanges(); window.getSelection()?.addRange(caret);
    });
    await highlight.waitFor();
    // Wait through both pulses until the real animation is holding its painted peak.
    await browser.evaluate(async () => {
      await new Promise<void>((resolve, reject) => {
        const deadline = performance.now() + 4000;
        const check = () => {
          const root = document.querySelector('[data-citation-highlighted="true"]');
          const animation = root?.getAnimations().find(a => a.id === "t3-assistant-citation-pulse");
          if (animation && Number(animation.currentTime) >= 1050 && Number(animation.currentTime) < 2000) resolve();
          else if (performance.now() > deadline) reject(new Error("Citation did not reach painted hold"));
          else requestAnimationFrame(check);
        };
        check();
      });
    });
  };
  await reveal();
  await app.screenshot("before-plain-escape-painted");
  await browser.keyboard.press("Escape");
  await app.screenshot("after-plain-escape");
  await expect(highlight).toHaveCount(0);
  await reveal();
  await app.screenshot("before-ime-escape-painted");
  await browser.evaluate(async () => {
    const composer = document.querySelector<HTMLElement>('[role="textbox"][contenteditable="true"]');
    if (!composer) throw new Error("Missing composer");
    composer.focus();
    composer.dispatchEvent(new CompositionEvent("compositionstart", {bubbles:true, data:""}));
    composer.dispatchEvent(new CompositionEvent("compositionupdate", {bubbles:true, data:"か"}));
    composer.dispatchEvent(new KeyboardEvent("keydown", {bubbles:true, cancelable:true, key:"Escape", code:"Escape", isComposing:true, keyCode:27}));
    composer.dispatchEvent(new CompositionEvent("compositionend", {bubbles:true, data:""}));
    await new Promise(resolve => setTimeout(resolve, 150));
  });
  await app.screenshot("after-ime-escape");
  await expect(highlight).toHaveCount(1);
});
