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

test("Saving a citation comment separates later typing and preserves the next word", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo");
  await t3.thread({ project, title: "Setup", messages: ["Hello"] });
  const results: string[] = [];
  for (const middle of [false, true]) {
    const launched = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Show the long stream", "--title", middle ? "Middle of text" : "End of text", "--provider", "devReplay", "--model", "bench-stream", "--json"]));
    const thread = JSON.parse(launched.stdout);
    await t3.open({ threadId: thread.threadId });
    await screen.getByText("compares it with the previous step", { exact: false }).first().waitFor({ state: "visible" });
    const composer = screen.getByRole("textbox");
    await composer.tap();
    if (middle) {
      await composer.pressSequentially("See world");
      await composer.press("Home");
      for (let i = 0; i < 4; i++) await composer.press("ArrowRight");
    }
    await browser.evaluate(() => {
      const first = [...document.querySelectorAll("[data-assistant-citation-source] p")].find(p => p.textContent?.includes("compares it with the previous step"));
      first?.scrollIntoView({ block: "center" });
    });
    await app.screenshot(middle ? "middle-quote-visible" : "end-quote-visible");
    await browser.keyboard.press("Shift");
    await browser.evaluate(() => {
      const phrase = "compares it with the previous step";
      const sources = [...document.querySelectorAll("[data-assistant-citation-source]")];
      for (const source of sources) {
        const walker = document.createTreeWalker(source, NodeFilter.SHOW_TEXT);
        for (let node = walker.nextNode(); node; node = walker.nextNode()) {
          const offset = node.textContent?.indexOf(phrase) ?? -1;
          if (offset < 0) continue;
          const target = node.parentElement!;
          target.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, isPrimary: true, button: 0 }));
          const range = document.createRange();
          range.setStart(node, offset); range.setEnd(node, offset + phrase.length);
          window.getSelection()?.removeAllRanges(); window.getSelection()?.addRange(range);
          document.dispatchEvent(new Event("selectionchange"));
          const rect = range.getBoundingClientRect();
          target.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, isPrimary: true, button: 0 }));
          target.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, button: 0, clientX: rect.right - 1, clientY: rect.top + rect.height / 2 }));
          return;
        }
      }
      throw new Error("Assistant quote not found");
    });
    await screen.getByRole("button", "Cite selection in composer").tap();
    const comment = screen.getByRole("textbox", "Comment on selected text");
    await comment.fill("queued note");
    await comment.press("Enter");
    await browser.keyboard.type(middle ? "x" : "later");
    await app.screenshot(middle ? "middle-typed-x" : "end-typed-later");
    await browser.keyboard.down("Control");
    await screen.getByRole("button", "Queue message", { exact: true }).tap();
    await browser.keyboard.up("Control");
    await screen.getByRole("button", "Edit queued message").waitFor({ state: "visible" });
    await browser.evaluate(() => {
      document.querySelector('[aria-label="Edit queued message"]')?.closest("li")?.scrollIntoView({ block: "center" });
    });
    await app.screenshot(middle ? "middle-queued-result" : "end-queued-result");
    results.push(await browser.evaluate(() => {
      const button = document.querySelector('[aria-label="Edit queued message"]');
      return button?.closest("li")?.textContent ?? "";
    }));
  }
  expect(results[0]).toContain("Comment: queued note later");
  expect(results[1]).toContain("Comment: queued notex world");
});
