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

test("Open citation comments survive history between real threads", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Citation demo");
  const settle = () => browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(animation => animation.effect?.getTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
    return null;
  });
  const seedFirst = (model: string) => t3.thread({ project, title: "First thread", messages: ["Show the demo"], model });
  let first;
  try { first = await seedFirst("showcase"); }
  catch (error) {
    if (!String(error).includes("Advertised models: default")) throw error;
    first = await seedFirst("default");
  }
  const second = await t3.thread({ project, title: "Second thread", messages: ["second"], model: "showcase" });
  await t3.open(second);
  await screen.getByRole("button", /^First thread,.*Citation demo$/).tap();
  await screen.getByText("Reads the manifest first", { exact: true }).waitFor();
  const bounds = await browser.evaluate(() => {
    const item = [...document.querySelectorAll('li')].find(el => el.textContent === 'Reads the manifest first');
    if (!item) throw new Error('Missing assistant bullet');
    const range = document.createRange(); range.selectNodeContents(item);
    const rect = range.getBoundingClientRect();
    return { left: rect.left, right: rect.right, y: rect.top + rect.height / 2 };
  });
  await browser.mouse.move(bounds.left, bounds.y);
  await browser.mouse.down();
  await browser.mouse.move(bounds.right, bounds.y);
  await browser.mouse.up();
  await screen.getByRole("button", "Cite selection in composer", { exact: true }).tap();
  const comment = screen.getByRole("textbox", "Comment on selected text", { exact: true });
  await comment.fill("Unsaved citation note before navigating");
  await settle();
  await app.screenshot("real-thread-comment-before-navigation");
  await browser.evaluate(() => { history.back(); return null; });
  await screen.getByRole("button", "Thread actions for Second thread").waitFor();
  await settle();
  await app.screenshot("second-real-thread-empty-composer");
  const destination = await browser.evaluate(() => document.querySelector('[data-chat-composer-form="true"] [contenteditable="true"]')?.textContent ?? "missing");
  await browser.evaluate(() => { history.forward(); return null; });
  await screen.getByRole("button", "Thread actions for First thread").waitFor();
  await screen.getByRole("button", /^(Add comment to citation|Edit citation comment)$/).tap();
  await comment.waitFor();
  await settle();
  await app.screenshot("real-thread-comment-after-returning");
  const realThreadComment = await browser.evaluate(() => document.querySelector<HTMLTextAreaElement>('[data-citation-comment-editor] textarea')!.value);
  await comment.press("Enter");
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  await screen.getByRole("heading", "New thread", { exact: true }).waitFor();
  await screen.getByRole("button", /^First thread,.*Citation demo$/).tap();
  await screen.getByRole("button", "Thread actions for First thread").waitFor();
  await screen.getByRole("button", /^(Add comment to citation|Edit citation comment)$/).tap();
  await comment.fill("Unsaved citation note before new-thread navigation");
  await settle();
  await app.screenshot("new-draft-comment-before-navigation");
  await browser.evaluate(() => { history.back(); return null; });
  await screen.getByRole("heading", "New thread", { exact: true }).waitFor();
  await settle();
  await app.screenshot("new-thread-empty-composer");
  const newDestination = await browser.evaluate(() => document.querySelector('[data-chat-composer-form="true"] [contenteditable="true"]')?.textContent ?? "missing");
  await browser.evaluate(() => { history.forward(); return null; });
  await screen.getByRole("button", "Thread actions for First thread").waitFor();
  await screen.getByRole("button", /^(Add comment to citation|Edit citation comment)$/).tap();
  await comment.waitFor();
  await settle();
  await app.screenshot("new-draft-comment-after-returning");
  const newThreadComment = await browser.evaluate(() => document.querySelector<HTMLTextAreaElement>('[data-citation-comment-editor] textarea')!.value);
  expect({ realThreadComment, destination, newThreadComment, newDestination }).toEqual({
    realThreadComment: "Unsaved citation note before navigating",
    destination: "",
    newThreadComment: "Unsaved citation note before new-thread navigation",
    newDestination: "",
  });
});
