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

test("Reply banner activation moves focus to the cited response", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("reply-focus-demo");
  const thread = await t3.thread({ project, title: "Reply focus demonstration", model: "todo-list", messages: ["First task", "Second task", "Third task", "Fourth task"] });
  await t3.open(thread);
  await screen.getByRole("button", "Reply to this response").first().tap();
  await browser.setViewport({ width: 1280, height: 520 });
  await browser.evaluate(() => {
    const cancel = document.querySelector('[aria-label="Cancel reply"]');
    const banner = cancel?.closest("[data-slot=composer-banner]");
    const link = banner?.querySelector("button:not([aria-label])") as HTMLElement | null;
    if (!link) throw new Error("Reply banner link not found");
    link.dataset.proofReplyLink = "true";
    let node = document.querySelector("[data-assistant-citation-source]")?.parentElement;
    while (node) {
      if (node.scrollHeight > node.clientHeight && /auto|scroll/.test(getComputedStyle(node).overflowY)) {
        node.scrollTop = node.scrollHeight;
        break;
      }
      node = node.parentElement;
    }
    link.focus({ preventScroll: true });
    const status = document.createElement("div");
    status.id = "proof-focus-status";
    status.style.cssText = "position:fixed;right:12px;top:58px;z-index:99999;background:#111;color:#fff;padding:10px 14px;border:2px solid #888;font:14px monospace;pointer-events:none;max-width:510px";
    const update = () => {
      const active = document.activeElement;
      const response = active?.closest("[data-assistant-citation-source]");
      status.textContent = response ? "Actual keyboard focus: assistant response" : active?.hasAttribute("data-proof-reply-link") ? "Actual keyboard focus: Replying to link" : "Actual keyboard focus: " + active?.tagName;
      status.style.borderColor = response ? "#4ade80" : "#fbbf24";
    };
    document.addEventListener("focusin", update);
    document.body.append(status);
    update();
    return null;
  });
  await app.screenshot("before-enter");
  await browser.keyboard.press("Enter");
  // The highlight marks completion of the app's scroll, on both revisions.
  await browser.locator("[data-citation-highlighted]").hover();
  await app.screenshot("after-enter");
  await expect(browser.locator("[data-assistant-citation-source]:focus")).toBeFocused();
});
