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

test("Details moved under a resting pointer open on the first click", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("documentation", {"notes.md": '<details open><summary>First section</summary>\n\nFirst body line one.\n\nFirst body line two.\n\nFirst body line three.\n\nFirst body line four.\n\n</details>\n\n<details><summary>Second section</summary>Hidden second body.</details>\n'});
  const thread = await t3.thread({project, title:"Markdown details", messages:['See :codex-file-citation{path="notes.md"}']});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent See/).tap();
  await screen.getByRole("link", /^notes\.md/).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("button", "First section").waitFor();
  const point = await browser.evaluate(() => {
    const buttons = Array.from(document.querySelectorAll<HTMLElement>('[data-markdown-details-summary]'));
    const first = buttons.find(b=>b.textContent?.includes('First section'))!;
    const second = buttons.find(b=>b.textContent?.includes('Second section'))!;
    const panel = first.parentElement!.querySelector<HTMLElement>('[data-slot="collapsible-panel"]')!;
    const rect = second.getBoundingClientRect();
    return {x:rect.x+rect.width/2,y:rect.y+rect.height/2-panel.getBoundingClientRect().height};
  });
  await browser.mouse.move(point.x, point.y);
  await browser.evaluate(() => {
    const first = Array.from(document.querySelectorAll<HTMLElement>('[data-markdown-details-summary]')).find(b=>b.textContent?.includes('First section'))!;
    const buttons = Array.from(document.querySelectorAll<HTMLElement>('button'));
    buttons[buttons.indexOf(first)-1]!.focus();
  });
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Enter");
  await browser.locator('[data-markdown-details-open="false"]').first().waitFor();
  await app.screenshot("summary-moved-under-resting-pointer");
  await browser.mouse.down();
  await browser.mouse.up();
  await app.screenshot("after-first-click");
  await expect(screen.getByText("Hidden second body.", {exact:true})).toBeVisible();
  await expect.poll(() => browser.evaluate(() => document.activeElement?.textContent?.trim())).toBe("Second section");
});
