import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Pin and undo unpin announce their results", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Accessibility demo");
  await t3.thread({ project, title: "Announcement example", messages: ["Hello"] });
  await t3.open();
  await screen.getByRole("button", "Announcement example, Done, Accessibility demo").tap();
  await browser.keyboard.press("Escape");
  await browser.evaluate(() => {
    const panel = document.createElement("pre");
    panel.id = "announcement-evidence";
    panel.style.cssText = "position:fixed;bottom:16px;right:16px;z-index:999999;background:#111;color:#fff;padding:18px;border:2px solid #aaa;font:16px monospace;max-width:650px;white-space:pre-wrap;pointer-events:none";
    panel.textContent = "Live region transcript (observed DOM)\nNo announcements received";
    document.body.append(panel);
    const messages: string[] = [];
    let last = "";
    new MutationObserver(() => {
      const text = Array.from(document.querySelectorAll('body > [aria-live="polite"][aria-atomic="true"]')).map(e => e.textContent).filter(Boolean).join(". ");
      if (text && text !== last) {
        messages.push(text);
        panel.textContent = "Live region transcript (observed DOM)\n" + messages.join("\n");
      }
      last = text;
    }).observe(document.body, { childList: true, subtree: true, characterData: true });
    (document.activeElement as HTMLElement)?.blur();
  });
  await browser.keyboard.press("Control+Shift+P");
  // Allow the app's 250ms focus-settle live-region queue to flush before capture.
  await browser.evaluate(() => new Promise<string>(resolve => setTimeout(() => resolve("settled"), 700)));
  await app.screenshot("pin-announcement");
  await browser.keyboard.press("Control+Shift+P");
  await screen.getByRole("button", "Undo", { exact: false }).first().tap();
  await browser.evaluate(() => new Promise<string>(resolve => setTimeout(() => resolve("settled"), 700)));
  await app.screenshot("undo-announcement");
  await expect(browser.locator("#announcement-evidence")).toHaveText("Live region transcript (observed DOM)\nPinned 1 thread\nUndid unpin of 1 thread");
});
