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

test("CJK trailing punctuation stays with a file chip", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("CJK file chips", { "src/foo.ts": "export const foo = 1;\n" });
  const thread = await t3.thread({ project, title: "CJK punctuation", model: "showcase", messages: ["Start"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("请查看这段处理逻辑对应的核心实现文件 [foo.ts](src/foo.ts)。然后在下一步中确认返回结果。");
  await composer.press("Enter");
  const chip = browser.locator('[data-user-message-body] a').filter({ hasText: "foo.ts" });
  await chip.waitFor();
  await screen.getByRole("button", "Stop generation").waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await browser.setViewport({ width: 452, height: 480 });
  await browser.mouse.move(220, 180);
  await browser.mouse.wheel(0, -1600);
  await chip.scrollIntoView();
  await browser.evaluate(() => {
    const body = [...document.querySelectorAll<HTMLElement>('[data-user-message-body]')].find(el => el.textContent?.includes('请查看'))!;
    body.scrollIntoView({ block: 'center', behavior: 'instant' });
  });
  await app.screenshot("cjk-file-chip-wrap");
  const sameLine = await browser.evaluate(() => {
    const body = [...document.querySelectorAll<HTMLElement>('[data-user-message-body]')].find(el => el.textContent?.includes('请查看'))!;
    const chip = body.querySelector('a')!.getBoundingClientRect();
    const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
    let node: Node | null;
    while ((node = walker.nextNode())) {
      const i = node.textContent?.indexOf('。') ?? -1;
      if (i < 0) continue;
      const range = document.createRange();
      range.setStart(node, i); range.setEnd(node, i + 1);
      const punctuation = range.getBoundingClientRect();
      return punctuation.top < chip.bottom && punctuation.bottom > chip.top;
    }
    return false;
  });
  expect(sameLine).toBe(true);
});
