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

test("Collapsing initially open Markdown details keeps summary focus", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("server", {
    "repro-details.md": "<details open>\n<summary>Notes</summary>\n\nDetails body\n\n</details>\n",
  });
  const thread = await t3.thread({ project, title: "Markdown details keyboard focus", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("repro-details.md");
  await screen.getByRole("option", "repro-details.md", { exact: false }).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("button", "Hide file explorer").tap();
  await screen.getByText("Details body", { exact: true }).waitFor();
  await screen.getByRole("button", "Save file", { exact: true }).tap();
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Tab");
  await browser.locator('[data-slot="collapsible-trigger"][aria-expanded="true"]:focus').waitFor();
  await app.screenshot("initially-open-summary-focused");
  await browser.keyboard.press("Enter");
  await browser.locator('[data-markdown-details-open="false"]').waitFor();
  const keptFocus = await browser.evaluate(() => document.activeElement?.textContent === "Notes");
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {}))); return null; });
  await app.screenshot("after-first-enter-collapsed");
  await browser.keyboard.press("Enter");
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {}))); return null; });
  await app.screenshot("after-second-enter");
  expect(keptFocus).toBe(true);
  await expect(screen.getByRole("button", "Notes", { exact: true })).toHaveAttribute("aria-expanded", "true");
  await expect(screen.getByRole("button", "Notes", { exact: true })).toBeFocused();
});
