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

test("Sidebar rename keeps its complete frame inside the title line", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("server");
  const thread = await t3.thread({ project, title: "New thread", messages: ["Hello"], model: "default" });
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  await browser.locator('[data-testid="sidebar-row-card"]').waitFor();
  await browser.evaluate(() => {
    document.querySelector('[data-testid="sidebar-row-card"]')!.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true, detail: 2 }));
    return null;
  });
  const input = screen.getByRole("textbox", "Thread title", { exact: true });
  await input.waitFor();
  await browser.evaluate(async () => {
    await document.fonts.ready;
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => undefined)));
    return null;
  });
  const measure = () => browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[aria-label="Thread title"]')!;
    const box = input.getBoundingClientRect();
    let left = 0, right = innerWidth;
    for (let parent = input.parentElement; parent; parent = parent.parentElement) {
      if (["hidden", "clip", "auto", "scroll"].includes(getComputedStyle(parent).overflowX)) {
        const bounds = parent.getBoundingClientRect();
        left = Math.max(left, bounds.left); right = Math.min(right, bounds.right);
      }
    }
    return { leftClipped: Math.max(0, left - box.left), rightClipped: Math.max(0, box.right - right) };
  });
  const doubleClick = await measure();
  await app.screenshot("double-click-rename");
  await input.press("Escape");
  await browser.evaluate(() => {
    const row = document.querySelector('[data-testid="sidebar-row-card"]')!;
    const box = row.getBoundingClientRect();
    row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: box.x + 80, clientY: box.y + 30 }));
    return null;
  });
  await screen.getByRole("menuitem", "Rename thread", { exact: true }).tap();
  await input.waitFor();
  await browser.evaluate(async () => {
    await document.fonts.ready;
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => undefined)));
    return null;
  });
  const contextMenu = await measure();
  await app.screenshot("context-menu-rename");
  expect({ doubleClick, contextMenu }).toEqual({ doubleClick: { leftClipped: 0, rightClipped: 0 }, contextMenu: { leftClipped: 0, rightClipped: 0 } });
});
