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

test("Scrolling a PR description does not recover focus into the condensed header", WEB, async ({t3, app, browser, screen}) => {
  await t3.project("Browse-mode proof");
  await browser.setViewport({width:1280,height:800});
  await browser.addInitScript(() => {
    let projectReady: (id: string) => void;
    (window as any).proofProjectReady = new Promise<string>(resolve => { projectReady = resolve; });
    const Native = window.WebSocket;
    window.WebSocket = class extends Native {
      constructor(...args: ConstructorParameters<typeof WebSocket>) {
        super(...args);
        this.addEventListener("message", event => {
          if (typeof event.data !== "string") return;
          const visit = (v: any) => {
            if (!v || typeof v !== "object") return;
            if (v.title === "Browse-mode proof" && v.workspaceRoot && v.id) projectReady(v.id);
            Object.values(v).forEach(visit);
          };
          try { visit(JSON.parse(event.data)); } catch {}
        });
      }
      send(data: any) {
        let req: any;
        try { req = JSON.parse(data); } catch { return super.send(data); }
        const reply = (value: unknown) => queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {data:JSON.stringify({_tag:"Exit",requestId:req.id,exit:{_tag:"Success",value}})})));
        const detail = {
          provider:"github",host:"github.com",projectId:req.payload?.projectId,projectTitle:"Browse-mode proof",workspaceRoot:"/synthetic",repository:"example/demo",number:1,
          title:"Accessible heading navigation", body: Array.from({length:80},(_,i)=>`## Description section ${i+1}\n\nSynthetic description paragraph ${i+1}. Browse mode scrolls this content without moving keyboard focus.`).join("\n\n"),
          url:"https://github.com/example/demo/pull/1",author:{login:"scenario-author",name:null,avatarUrl:null},viewer:"scenario-author",state:"open",isDraft:false,mergeability:"mergeable",additions:1,deletions:0,changedFiles:1,headBranch:"feature",baseBranch:"main",createdAt:"2026-09-01T00:00:00Z",updatedAt:"2026-09-01T00:00:00Z",mergedAt:null,closedAt:null,reviewers:[],labels:[],checks:[],comments:[],commentCount:0,commentsTruncated:false,reviewThreads:[],commits:[],mergeCapabilities:{merge:false,squash:false,rebase:false},
          capabilities:{diff:true,comment:false,search:true,actions:[],mergeMethods:[],review:{inlineComment:false,reply:false,resolve:false,verdicts:[]},reviewers:{request:false,listCandidates:false},edit:{changeRequest:false,comment:false}},viewerPermissions:{actions:[],comment:false,resolve:false,verdicts:[],requestReviewers:false}
        };
        if (req.tag === "pullRequests.detail") return reply(detail);
        if (req.tag === "pullRequests.activity") return reply({comments:[],commentCount:0,commentsTruncated:false,reviewThreads:[],commits:[]});
        if (req.tag === "pullRequests.checks") return reply({state:"open",checks:[]});
        if (req.tag === "pullRequests.list") return reply({viewers:{},providers:[],entries:[],errors:[],truncated:false,nextCursors:{}});
        if (req.tag === "pullRequests.linkedThreads") return reply([]);
        return super.send(data);
      }
    } as typeof WebSocket;
  });
  await t3.open();
  const id = await browser.evaluate(()=> (window as any).proofProjectReady);
  await app.open(`/pull-requests?repository=example%2Fdemo&number=1&selectedProjectId=${id}`);
  await screen.getByText("Description section 1",{exact:true}).waitFor();
  await browser.evaluate(() => {
    const button = [...document.querySelectorAll<HTMLButtonElement>("button")].find(b=> b.getAttribute("aria-label") === "Open pull request #1 on host" && !b.closest("[inert]"));
    if (!button) throw new Error("Expanded host button not found");
    button.focus();
    (window as any).focusCalls=[];
    const focus = HTMLElement.prototype.focus;
    HTMLElement.prototype.focus = function(...args) {
      (window as any).focusCalls.push(this.getAttribute("aria-label") || this.textContent);
      return focus.apply(this,args);
    };
  });
  await app.screenshot("expanded-header");
  await browser.evaluate(() => {
    const section = [...document.querySelectorAll<HTMLElement>("div")].find(e=> e.classList.contains("overflow-y-auto") && e.textContent?.includes("Description section 80") && e.scrollHeight > e.clientHeight);
    if (!section) throw new Error("Summary scroller not found");
    section.scrollTop=section.scrollHeight;
    return new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true)))));
  });
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
  });
  await browser.evaluate(() => {
    const calls = (window as any).focusCalls as string[];
    const report=document.createElement("aside");
    report.style.cssText="position:fixed;bottom:18px;left:280px;right:18px;background:#151923;color:#fff;padding:16px;border:2px solid #6b8cff;z-index:99999;font:16px monospace;white-space:pre-wrap";
    report.textContent=`Browse-mode scroll: no DOM focus movement requested\nProgrammatic focus() calls after scroll: ${calls.length}\n${calls.join("\n")}\nActive element: ${document.activeElement?.getAttribute("aria-label") || document.activeElement?.tagName}`;
    document.body.append(report);
  });
  await app.screenshot("after-browse-scroll");
  expect(await browser.evaluate(()=> (window as any).focusCalls.length), "Scrolling must not programmatically move focus to the condensed PR header").toBe(0);
});
