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

// Synthetic forge reads keep this proof independent of a writable public PR.
// The app, diff viewer, editor and background-refresh subscription are real.
test("An unfinished PR inline comment survives another file changing", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("inline-review", {"a.ts": "before()\none()\ntwo()\n", "b.ts": "before()\none()\ntwo()\n"});
  const thread = await t3.thread({project, title: "Review the changes", messages: ["first"]});
  await browser.setViewport({width: 1440, height: 1000});
  await browser.addInitScript(() => {
    let changed = false;
    const streams: Array<() => void> = [];
    const patch = (path: string, addition: string) => `diff --git a/${path} b/${path}\nindex 1111111..2222222 100644\n--- a/${path}\n+++ b/${path}\n@@ -1,3 +1,3 @@\n-before()\n+${addition}\n one()\n two()\n`;
    const fetch = window.fetch;
    window.fetch = async function(input, init) {
      const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
      if (url.includes("/api/pull-requests/diff")) {
        const result = {patch: patch("a.ts", "afterA()") + patch("b.ts", changed ? "afterBRefresh()" : "afterB()"), truncated: false, nextCursor: null};
        return new Response(JSON.stringify(result), {headers: {"Content-Type": "application/json"}});
      }
      return fetch.call(this, input, init);
    };
    Object.assign(window, {refreshOtherFile: () => {changed = true; for (const emit of streams) emit();}});
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const r = typeof data === "string" ? JSON.parse(data) : null;
      if (r?._tag !== "Request" || !r.tag.startsWith("pullRequests.")) return send.call(this, data);
      const reply = (value: unknown) => queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {data: JSON.stringify({_tag:"Exit", requestId:r.id, exit:{_tag:"Success", value}})})));
      if (r.tag === "pullRequests.subscribeRefreshes") {
        const emit = () => this.dispatchEvent(new MessageEvent("message", {data:JSON.stringify({_tag:"Chunk", requestId:r.id, values:[changed ? 1 : 0]})}));
        streams.push(emit); queueMicrotask(emit); return;
      }
      if (r.tag.includes("subscribe")) return send.call(this, data);
      const detail = {provider:"github", projectId:r.payload.projectId, projectTitle:"inline-review", workspaceRoot:"/workspace/inline-review", repository:"example/inline-review", number:42, title:"Keep inline review drafts during refresh", body:"Two files changed. Review a.ts while b.ts updates.", url:"https://github.com/example/inline-review/pull/42", author:{login:"reviewer",name:null,avatarUrl:null}, viewer:"reviewer", state:"open", isDraft:false, mergeability:"mergeable", additions:2, deletions:2, changedFiles:2, headBranch:"feature", baseBranch:"main", createdAt:"2026-11-01T00:00:00Z", updatedAt:"2026-11-01T00:00:00Z", mergedAt:null, closedAt:null, reviewers:[],labels:[],checks:[], mergeCapabilities:{merge:false,squash:false,rebase:false}, capabilities:{diff:true,comment:true,search:true,actions:[],mergeMethods:[],review:{inlineComment:true,reply:false,resolve:false,verdicts:[]},reviewers:{request:false,listCandidates:false},edit:{changeRequest:false,comment:false}},viewerPermissions:{actions:[],comment:true,resolve:false,verdicts:[],requestReviewers:false}};
      switch(r.tag) {
        case "pullRequests.detail": case "pullRequests.summary": reply(detail); return;
        case "pullRequests.activity": reply({comments:[],commentCount:0,commentsTruncated:false,reviewThreads:[],commits:[]}); return;
        case "pullRequests.filesViewed": reply({files:[],truncated:false}); return;
        case "pullRequests.changeBreakdown": case "pullRequests.stack": case "pullRequests.checks": reply(null); return;
        case "pullRequests.linkedThreads": reply({threads:[]}); return;
        case "pullRequests.routing": case "pullRequests.routingIdentity": reply({accountId:"scenario",host:"github.com",provider:"github",viewer:"reviewer",projectTitle:"inline-review",workspaceRoot:"/workspace/inline-review"}); return;
        case "pullRequests.list": reply({viewers:{"github.com":"reviewer"},providers:[],entries:[],errors:[],truncated:false,nextCursors:{}}); return;
      }
      return send.call(this,data);
    };
  });
  await t3.open(thread);
  const projects = await browser.evaluate(async () => (await (await fetch("/api/projects")).json()).projects);
  const id = projects.find((p: {title:string}) => p.title === "inline-review").id;
  await t3.open(`/pull-requests?repository=example%2Finline-review&number=42&selectedProjectId=${id}&selectedHost=github.com`);
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  await screen.getByRole("button", "Code", {exact:true}).tap();
  await screen.getByRole("button", "Expand all files", {exact:true}).tap();
  await screen.getByRole("status", "Loading pull request diff...", {exact:true}).waitFor({state:"hidden"});
  await browser.locator("[data-column-number]").first().waitFor();
  // Locate the real diff gutter inside Pierre's shadow DOM, then use pointer input.
  const point = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const line = host.shadowRoot?.querySelector<HTMLElement>('[data-line-type="change-addition"][data-column-number="1"], [data-column-number="1"]');
      if(line) {const r=line.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2};}
    }
    throw new Error("No diff gutter");
  });
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  const comment = browser.locator('textarea[aria-label^="Comment on lines"]');
  await comment.fill("Keep this unfinished review on a.ts line 1");
  await app.screenshot("draft-before-refresh");
  await browser.evaluate(() => { (window as unknown as {refreshOtherFile:()=>void}).refreshOtherFile(); });
  // Wait for changed content in b.ts, without asserting unrelated behavior.
  await browser.evaluate(() => new Promise<void>((resolve, reject) => {
    const observers: MutationObserver[] = [];
    const seen = new Set<Node>();
    const timeout = setTimeout(() => { observers.forEach(o => o.disconnect()); reject(new Error("Changed b.ts did not render")); }, 20000);
    const check = () => {
      for (const h of document.querySelectorAll("*")) {
        if (!h.shadowRoot) continue;
        if (h.shadowRoot.textContent?.includes("afterBRefresh()")) { clearTimeout(timeout); observers.forEach(o => o.disconnect()); resolve(); return; }
        if (!seen.has(h.shadowRoot)) { seen.add(h.shadowRoot); const o = new MutationObserver(check); o.observe(h.shadowRoot,{subtree:true,childList:true,characterData:true}); observers.push(o); }
      }
    };
    const o = new MutationObserver(check); o.observe(document,{subtree:true,childList:true}); observers.push(o); check();
  }));
  await screen.getByRole("status", "Loading pull request diff...", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("draft-after-refresh");
  await expect(comment).toHaveValue("Keep this unfinished review on a.ts line 1");
  await expect(comment).toHaveAttribute("aria-label", "Comment on lines a.ts:1");
  await comment.fill("Keep this unfinished review on a.ts line 1 — continued typing");
  await app.screenshot("continued-editing");
  await expect(comment).toHaveValue("Keep this unfinished review on a.ts line 1 — continued typing");
});
