/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";

// Synthetic host responses keep the content identical; all focus and scrolling is the real client.
test("Pull request tabs scroll after opening, plain text clicks and loading", WEB, async ({ t3, app, browser, screen }) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  await writeFile(settingsPath, JSON.stringify({...JSON.parse(await readFile(settingsPath,"utf8")),reviewGuidesEnabled:true}));
  const project = await t3.project("Keyboard scrolling");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/example/keyboard-demo.git"], { cwd: project }));
  const thread = await t3.thread({ project, title: "Review keyboard scrolling", messages: ["Please review https://github.com/example/keyboard-demo/pull/42"] });
  await browser.setViewport({ width: 1280, height: 800 });
  const patch = "diff --git a/scrolling.ts b/scrolling.ts\nnew file mode 100644\nindex 0000000..1234567\n--- /dev/null\n+++ b/scrolling.ts\n@@ -0,0 +1,240 @@\n" + Array.from({length:240}, (_,i) => `+export const section${i+1} = "Keyboard scrolling example ${i+1}";`).join("\n") + "\n";
  let releaseDiff = () => {};
  const diffReady = new Promise<void>(resolve => { releaseDiff = resolve; });
  await browser.route(/\/api\/pull-requests\/diff(?:\?|$)/, async route => {
    await diffReady;
    return route.fulfill({ json: { patch, truncated:false, nextCursor:null } });
  });
  await browser.addInitScript(() => {
    localStorage.setItem("t3code:client-settings:v1", JSON.stringify({diffFilesCollapsed:false}));
    const date = "2026-10-01T12:00:00Z";
    const actor = { login: "reviewer", name:null, avatarUrl:null };
    const paragraphs = (prefix: string) => Array.from({length:60}, (_,i) => `${prefix} ${String(i+1).padStart(2,"0")} — Check that keyboard navigation keeps the review moving through the active pane. This paragraph provides enough content to make page scrolling visible.`).join("\n\n");
    const release: Record<string, () => void> = {};
    Object.assign(window, { releaseFixture: (tag:string) => release[tag]?.() });
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const request = typeof data === "string" ? JSON.parse(data) : null;
      if (request?._tag !== "Request") return send.call(this,data);
      const p = request.payload ?? {};
      const detail = { provider:"github", projectId:p.projectId, projectTitle:"Keyboard scrolling", workspaceRoot:"/workspace", repository:"example/keyboard-demo", number:42, title:"Make review panes keyboard accessible", body:paragraphs("Description section"), url:"https://github.com/example/keyboard-demo/pull/42", author:actor, viewer:"reviewer", state:"open", isDraft:false, mergeability:"mergeable", additions:240, deletions:0, changedFiles:1, headBranch:"keyboard-scroll", baseBranch:"main", headSha:"1234567890abcdef", createdAt:date, updatedAt:date, mergedAt:null, closedAt:null, reviewers:[], labels:[], checks:[], 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} };
      const activity = { comments:Array.from({length:24}, (_,i) => ({ id:`comment-${i}`, kind:"review", author:actor, body:`Timeline entry ${String(i+1).padStart(2,"0")}\n\n${paragraphs("Review note").split("\n\n").slice(0,3).join("\n\n")}`, createdAt:new Date(Date.parse(date)+i*60000).toISOString(), url:null,path:null,reviewState:"APPROVED" })),commentCount:24,commentsTruncated:false,reviewThreads:[],commits:[] };
      const replies: Record<string,unknown> = {
        "pullRequests.routingIdentity":{accountId:"scenario",host:"github.com",provider:"github",viewer:"reviewer"},
        "pullRequests.routing":{accountId:"scenario",host:"github.com",provider:"github",viewer:"reviewer",projectTitle:"Keyboard scrolling",workspaceRoot:"/workspace"},
        "pullRequests.detail":detail, "pullRequests.preview":detail, "pullRequests.summary":detail,
        "pullRequests.activity":activity, "pullRequests.checks":{state:"open",checks:[]},
        "pullRequests.linkedThreads":{threads:[]}, "pullRequests.stack":{id:"stack",number:42,url:detail.url,base:"main",layers:[]},
        "pullRequests.filesViewed":{files:[],truncated:false}, "pullRequests.changeBreakdown":null,
        "pullRequests.reviewGuide":{guide:{headSha:detail.headSha,generatedAt:date,modelSelection:{instanceId:"devReplay",model:"showcase"},stops:[{title:"Keyboard review tour",summary:paragraphs("Guide section"),attention:null,excerpts:[],files:[],notes:[],questions:[]}]},run:null,currentHeadSha:detail.headSha},
      };
      if (!(request.tag in replies)) return send.call(this,data);
      const reply = () => this.dispatchEvent(new MessageEvent("message", {data:JSON.stringify({_tag:"Exit",requestId:request.id,exit:{_tag:"Success",value:replies[request.tag]}})}));
      if (["pullRequests.activity","pullRequests.reviewGuide"].includes(request.tag)) release[request.tag] = reply;
      else setTimeout(reply, request.tag === "pullRequests.detail" ? 1500 : 0);
    };
  });
  await t3.open(thread);
  const collapsed = screen.getByRole("button", /^Agent Please review/);
  await collapsed.waitFor();
  await collapsed.tap();
  await screen.getByRole("link", /https:\/\/github.com\/example\/keyboard-demo\/pull\/42/).first().tap();
  const summary = browser.locator('[data-pull-request-summary-scroll]:visible');
  await summary.waitFor();
  // Native smooth scrolling must finish before the evidence is sampled.
  const settle = () => browser.evaluate(async () => { await new Promise(r => setTimeout(r,1100)); return null; });
  const measurements: Array<{label:string,top:number}> = [];
  const top = () => browser.evaluate(() => {
    const panel = document.querySelector('[data-workspace-area="panel"]') ?? document.querySelector('[aria-label="Workspace panel"]');
    const candidates = [...(panel ?? document).querySelectorAll<HTMLElement>("*")].filter(e => e.clientHeight>100 && e.scrollHeight>e.clientHeight+80 && e.getBoundingClientRect().width>150 && e.getBoundingClientRect().height>100 && getComputedStyle(e).visibility!=="hidden" && /auto|scroll/.test(getComputedStyle(e).overflowY));
    const element = candidates.find(e => e.hasAttribute("data-pull-request-summary-scroll")) ?? candidates.sort((a,b)=>b.scrollHeight-a.scrollHeight)[0];
    if (!element) throw new Error("No active tab scroller");
    return element.scrollTop;
  });
  const capture = async (label:string) => {
    await settle();
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt=0; attempt<6; attempt++) {
      await browser.evaluate(async () => { await new Promise(r => setTimeout(r,500)); return null; });
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) {
        measurements.push({label,top:await top()}); return;
      }
      previous = current;
    }
    throw new Error(`Screenshots did not settle: ${label}`);
  };
  await capture("01-summary-open-top");
  await browser.keyboard.press("PageDown"); await browser.keyboard.press("PageDown");
  await capture("02-summary-open-pagedown");
  await browser.evaluate(() => { document.querySelector('[data-pull-request-summary-scroll]')?.scrollTo(0,0); });
  await settle();
  await screen.getByText(/^Description section 01/).tap();
  await capture("03-summary-click-top");
  await browser.keyboard.press("ArrowDown"); await browser.keyboard.press("PageDown");
  await capture("04-summary-click-arrow-page");
  const navigation: Array<{tab:string,end:number,pageUp:number,home:number}> = [];
  const checkNavigation = async (tab:string) => {
    await browser.keyboard.press("End"); await capture(`${tab}-end`);
    const end = await top();
    await browser.keyboard.press("ArrowUp"); await browser.keyboard.press("PageUp"); await capture(`${tab}-arrow-up-page-up`);
    const pageUp = await top();
    await browser.keyboard.press("Home"); await capture(`${tab}-home`);
    navigation.push({tab,end,pageUp,home:await top()});
  };
  // Open each tab while its response is held, then click the loading body before releasing it.
  const pairs: Array<[number,number]> = [[0,1],[2,3]];
  for (const tab of ["Timeline", "Code", "Guide"]) {
    await screen.getByRole("button", tab, {exact:true}).tap();
    const panel = browser.locator('[data-workspace-area="panel"]');
    await panel.click({position:{x:180,y:380}});
    if (tab === "Code") releaseDiff();
    else await browser.evaluate((tag:string) => { (window as unknown as {releaseFixture:(tag:string)=>void}).releaseFixture(tag); return null; }, tab === "Timeline" ? "pullRequests.activity" : "pullRequests.reviewGuide");
    await settle(); await settle();
    const index = measurements.length;
    await capture(`05-${tab.toLowerCase()}-loaded-top`);
    await browser.keyboard.press("PageDown"); await browser.keyboard.press("PageDown");
    await capture(`06-${tab.toLowerCase()}-loaded-pagedown`);
    pairs.push([index,index+1]);
    await browser.keyboard.press("Home"); await settle();
    // At the top, click plain text inside the scrollable content, away from toolbar controls.
    if (tab === "Timeline") await screen.getByText("Timeline entry 24", {visible:true}).tap();
    else if (tab === "Guide") await screen.getByText(/^Guide section 01/, {visible:true}).tap();
    else await browser.locator('.diff-render-surface:visible').click({position:{x:220,y:180}});
    const clicked = measurements.length;
    await capture(`07-${tab.toLowerCase()}-click-top`);
    await browser.keyboard.press("ArrowDown"); await browser.keyboard.press("PageDown");
    await capture(`08-${tab.toLowerCase()}-click-arrow-page`);
    pairs.push([clicked,clicked+1]);
    await checkNavigation(tab.toLowerCase());
  }
  await screen.getByRole("button", "Summary", {exact:true}).tap();
  await screen.getByText(/^Description section 01/, {visible:true}).tap();
  await checkNavigation("summary");
  console.log("SCROLL_MEASUREMENTS", JSON.stringify({measurements,navigation}));
  for (const [before,after] of pairs) {
    expect(measurements[after].top - measurements[before].top, measurements[after].label).toBeGreaterThan(200);
  }
  for (const row of navigation) {
    expect(row.end-row.pageUp, `${row.tab}: ArrowUp and PageUp`).toBeGreaterThan(100);
    expect(row.pageUp, `${row.tab}: End reached beyond one page`).toBeGreaterThan(200);
    expect(row.home, `${row.tab}: Home`).toBeLessThan(1);
  }
});
