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

test("Pointer highlighting leaves partly hidden thread search results still", WEB, async ({t3, app, browser, screen}) => {
  const capture = async (label: string) => {
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
    await app.screenshot(label);
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 600)));
  };
  const project = await t3.project("Widget demo");
  let thread;
  for (let i=1;i<=26;i++) thread = await t3.thread({project,title:`Refactor widget ${i}`,messages:["Start"]});
  await browser.setViewport({width:1280,height:600});
  await t3.open(thread!);
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  await browser.evaluate(() => new Promise<void>(resolve => {
    const done = () => !document.body.textContent?.includes("Syncing messages");
    if (done()) return resolve();
    const observer = new MutationObserver(() => {if(done()){observer.disconnect();resolve();}});
    observer.observe(document.body,{childList:true,subtree:true,characterData:true});
  }));
  const search = screen.getByRole("combobox", "Search threads");
  await search.fill("widget");
  await screen.getByRole("option", "Refactor widget 26", {exact:false}).waitFor();
  const read = () => browser.evaluate(() => {
    const list = document.querySelector('#sidebar-thread-search-results')!;
    const viewport = list.closest('[data-slot="scroll-area-viewport"]')!;
    const edge = viewport.getBoundingClientRect();
    const rows = Array.from(list.querySelectorAll('[role="option"]'));
    const partial = rows.find(row => {const r=row.getBoundingClientRect();return r.top<edge.bottom && r.bottom>edge.bottom;});
    if (!partial) throw new Error('No partly visible result');
    const r=partial.getBoundingClientRect();
    return {top:viewport.scrollTop,x:r.left+100,y:(r.top+edge.bottom)/2,title:partial.textContent};
  });
  const before = await read();
  await capture("before-hover");
  await browser.mouse.move(before.x,before.y);
  await capture("after-hover");
  const after = await browser.evaluate(() => document.querySelector('#sidebar-thread-search-results')!.closest('[data-slot="scroll-area-viewport"]')!.scrollTop);
  await browser.mouse.move(120,70);
  await search.press("ArrowDown");
  await capture("keyboard-arrow-down");
  for (let i=0;i<13;i++) await search.press("ArrowUp");
  await capture("keyboard-arrow-up");
  expect(after).toBe(before.top);
});
