/// <reference lib="dom" />
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { chromium } from "playwright-core";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Expanded command output is readable independently of its toggle", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  const thread = await t3.thread({ project, title: "Replay: showcase", messages: ["Give me a short tour"], model: "showcase" });
  await browser.addInitScript(() => {
    const mask = () => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        const value = node.nodeValue ?? "";
        if (value.includes("/home/")) node.nodeValue = value.replace(/\/home\/\S+/g, "[workspace path hidden]");
        if (/^f-[a-z0-9-]+$/.test(value)) node.nodeValue = "[machine label hidden]";
      }
    };
    addEventListener("DOMContentLoaded", () => {
      new MutationObserver(mask).observe(document.body, { childList: true, subtree: true, characterData: true });
      mask();
    });
  });
  await t3.open(thread);
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  await screen.getByRole("button", "Changed 1 file", { exact: false }).tap();
  const command = screen.getByRole("button", "vp test run", { exact: true });
  await command.press("Enter");
  await browser.keyboard.press("Shift+Tab");
  await browser.keyboard.press("Tab");
  await expect(screen.getByText("Test Files", { exact: false }).first()).toBeVisible();
  await app.screenshot("expanded-command-output");
  const evidence = await browser.evaluate(() => {
    const toggle = document.querySelector('[role="button"][aria-label="vp test run"]');
    const output = [...document.querySelectorAll("div, pre, span")].find((node) => node.textContent?.includes("Test Files") && ![...node.children].some((child) => child.textContent?.includes("Test Files")));
    const controlled = document.getElementById(toggle?.getAttribute("aria-controls") ?? "");
    return {
      expanded: toggle?.getAttribute("aria-expanded"),
      output: output?.textContent ?? null,
      outputInsideButton: Boolean(output?.closest('[role="button"], button')),
      controlsOutput: Boolean(controlled && output && controlled.contains(output)),
    };
  });
  console.log("ACCESSIBILITY_EVIDENCE", JSON.stringify(evidence));
  const connected = await chromium.connectOverCDP("http://127.0.0.1:19226");
  const context = connected.contexts().find((candidate) => candidate.pages().some((page) => page.url().includes("127.0.0.1:")));
  const page = context?.pages().find((candidate) => candidate.url().includes("127.0.0.1:"));
  if (!context || !page) throw new Error("Scenario page not found");
  const cdp = await context.newCDPSession(page);
  const tree = await cdp.send("Accessibility.getFullAXTree");
  const relevant = tree.nodes.filter((node) => node.name?.value?.includes("Test Files") || node.name?.value === "vp test run");
  const rows = relevant.map((node) => {
    const ancestors = [];
    let parent = tree.nodes.find((candidate) => candidate.nodeId === node.parentId);
    while (parent) {
      ancestors.push({ role: parent.role?.value ?? null, name: parent.name?.value ?? null });
      parent = tree.nodes.find((candidate) => candidate.nodeId === parent?.parentId);
    }
    return { role: node.role?.value ?? null, name: node.name?.value ?? null, ignored: node.ignored, ancestors };
  });
  console.log("CHROMIUM_AX_EVIDENCE", JSON.stringify(rows));
  await cdp.detach();
  await connected.close();
  if (process.env.T3_PROOF_OUTPUT_DIR) {
    await writeFile(join(process.env.T3_PROOF_OUTPUT_DIR, `accessibility-${evidence.controlsOutput ? "after" : "before"}.json`), JSON.stringify({ evidence, chromiumAX: rows }, null, 2));
  }
  await browser.evaluate((audit) => {
    const panel = document.createElement("aside");
    panel.style.cssText = "position:fixed;right:16px;bottom:16px;width:360px;padding:18px;z-index:99999;background:#fff;color:#111;border:2px solid #555;font:14px/1.5 monospace;white-space:pre-wrap;box-shadow:0 2px 12px #888";
    const outputNodes = audit.rows.filter((node) => node.role === "StaticText" && node.name?.includes("Test Files"));
    panel.textContent = "LIVE ACCESSIBILITY AUDIT\n(inspection overlay, not product UI)\n\n" +
      "Toggle expanded: " + audit.evidence.expanded + "\n" +
      "Output inside button: " + audit.evidence.outputInsideButton + "\n" +
      "aria-controls links output: " + audit.evidence.controlsOutput + "\n\n" +
      "Chromium AX output ancestors:\n" + outputNodes.map((node) => node.ancestors.map((ancestor) => ancestor.role).join(" > ")).join("\n");
    document.body.append(panel);
  }, { evidence, rows });
  await app.screenshot("accessibility-audit");
  expect(evidence.output).toContain("Test Files");
  expect(evidence.outputInsideButton).toBe(false);
  expect(evidence.expanded).toBe("true");
  expect(evidence.controlsOutput).toBe(true);
});
