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

test("Find announces user navigation but not streamed recounts", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => {
    const maskPaths = () => {
      if (!document.body) return;
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (/\/(home|Users)\//.test(node.textContent ?? "") && node.parentElement) {
          node.parentElement.style.visibility = "hidden";
        }
      }
    };
    new MutationObserver(maskPaths).observe(document, { subtree: true, childList: true, characterData: true });
  });
  const project = await t3.project("Find announcement demo");
  const thread = await t3.thread({ project, title: "Find announcement demo", model: "showcase", messages: ["Explain the project and the module"] });
  await t3.open(thread);
  await screen.getByRole("textbox").tap();
  await browser.keyboard.press("Control+f");
  const query = screen.getByRole("searchbox", "Find in thread");
  await query.fill("the");
  await screen.getByRole("button", "Next match").tap();
  await browser.evaluate(() => {
    const bar = document.querySelector("[data-thread-find-bar]")!;
    const live = bar.querySelector('[aria-live="polite"]')!;
    const panel = document.createElement("pre");
    panel.id = "announcement-monitor";
    panel.style.cssText = "position:fixed;left:16px;top:100px;z-index:99999;background:#111827;color:#fff;padding:16px;border:2px solid #60a5fa;font:14px/1.6 monospace;max-width:650px;white-space:pre-wrap;pointer-events:none";
    document.body.append(panel);
    const state = { phase: "background", records: [] as { phase: string; text: string }[], last: live.textContent ?? "" };
    (window as any).__findProof = state;
    const render = () => { panel.textContent = "DOM live-region monitor (not NVDA audio)\n" + "Phase: " + state.phase + "\nCurrent aria-live text: " + live.textContent + "\n" + "Background mutations: " + state.records.filter(r => r.phase === "background").length + "\nRecent changes (last 12):\n" + (state.records.slice(-12).map(r => r.phase + ": " + r.text).join("\n") || "No live-region changes recorded."); };
    new MutationObserver(() => {
      const text = live.textContent ?? "";
      if (text !== state.last) { state.records.push({ phase: state.phase, text }); state.last = text; }
      render();
    }).observe(live, { subtree: true, childList: true, characterData: true });
    render();
  });
  const composer = screen.getByRole("textbox");
  await composer.fill("Tell me more about the project");
  await composer.press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "visible" });
  await app.screenshot("streaming-recount");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await screen.getByRole("button", "Next match").waitFor({ state: "visible" });
  await app.screenshot("background-finished");
  await browser.evaluate(() => { (window as any).__findProof.phase = "next"; });
  await screen.getByRole("button", "Next match").tap();
  await browser.evaluate(() => { (window as any).__findProof.phase = "previous"; });
  await screen.getByRole("button", "Previous match").tap();
  await browser.evaluate(() => { (window as any).__findProof.phase = "query"; });
  await query.fill("project");
  await screen.getByRole("button", "Next match").tap();
  await app.screenshot("user-driven-announcements");
  const records = await browser.evaluate(() => (window as any).__findProof.records);
  expect(records.filter((r: any) => r.phase === "background")).toEqual([]);
  expect(records.some((r: any) => r.phase === "next")).toBe(true);
  expect(records.some((r: any) => r.phase === "previous")).toBe(true);
  expect(records.some((r: any) => r.phase === "query")).toBe(true);
});
