/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

test("Escape cancels diff comments and review replies while keeping the workspace sheet open", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { ".git/config": '[remote "origin"]\n  url = https://github.com/example/demo.git\n  fetch = +refs/heads/*:refs/remotes/origin/*\n', "notes.txt": "First line\nOld second line\nLast line\n" });
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/notes.txt`, "First line\nNew second line\nLast line\n");
  }));
  const thread = await t3.thread({ project, title: "Review notes", messages: ["Review https://github.com/example/demo/pull/42"] });
  await browser.setViewport({ width: 900, height: 800 });
  // Seed only host data; the production app, editor and keyboard/dismiss handlers run unchanged.
  await browser.addInitScript(() => {
    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 answer = (value: unknown) => queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {
        data: JSON.stringify({_tag:"Exit",requestId:request.id,exit:{_tag:"Success",value}})
      })));
      if (request.tag === "pullRequests.detail") {
        answer({ ...request.payload, provider:"github", projectTitle:"demo", workspaceRoot:"/workspace/demo",
          title:"Review the implementation notes",body:"Update the second line of the notes.",url:"https://github.com/example/demo/pull/42",
          author:{login:"author",name:null,avatarUrl:null},state:"open",isDraft:false,mergeability:"mergeable",
          additions:1,deletions:1,changedFiles:1,headBranch:"notes-update",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,actions:[],mergeMethods:[],search:true,
            review:{inlineComment:true,reply:true,resolve:false,verdicts:[]},reviewers:{request:false,listCandidates:false}},
          viewerPermissions:{actions:[],comment:true,resolve:false,verdicts:[],requestReviewers:false}
        }); return;
      }
      if (request.tag === "pullRequests.activity") {
        answer({comments:[],commentCount:0,commentsTruncated:false,commits:[],reviewThreads:[{
          id:"review-conversation",path:"notes.txt",line:2,side:"right",isResolved:false,isOutdated:false,
          comments:[{id:"review-comment",author:{login:"reviewer",name:null,avatarUrl:null},
            body:"Could you clarify this line?",createdAt:"2026-11-01T00:00:00Z",url:null}]
        }]}); return;
      }
      if (request.tag === "pullRequests.checks") { answer({state:"open",checks:[]}); return; }
      if (request.tag === "pullRequests.filesViewed") { answer({files:[],truncated:false}); return; }
      return send.call(this,data);
    };
  });
  await browser.route(/\/api\/pull-requests\/diff$/, route => route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({
    patch:"diff --git a/notes.txt b/notes.txt\nindex 1111111..2222222 100644\n--- a/notes.txt\n+++ b/notes.txt\n@@ -1,3 +1,3 @@\n First line\n-Old second line\n+New second line\n Last line\n",
    truncated:false,nextCursor:null
  })}));


  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  const settle = async () => {
    await browser.mouse.move(400, 500);
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations({subtree:true}).filter(a => a.effect?.getTiming().iterations !== Infinity).map(a=>a.finished.catch(()=>{})));
    });
  };
  const sheet = screen.getByRole("dialog", "Workspace panel");
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("button", "Expand notes.txt").tap();
  const point = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const line = Array.from(host.shadowRoot?.querySelectorAll<HTMLElement>('[data-line]') ?? []).find(line => line.textContent?.includes('New second line'));
      if (line) { const r = line.getBoundingClientRect(); return {x:r.x+12, y:r.y+r.height/2}; }
    }
    return null;
  });
  if (!point) throw new Error("diff line 2 not found");
  await browser.mouse.move(point.x, point.y);
  const utility = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const root = host.shadowRoot;
      const button = root?.querySelector<HTMLElement>('[data-utility-button]');
      if (button) { const r=button.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; }
    }
    return null;
  });
  if (!utility) throw new Error("gutter utility not found");
  await browser.mouse.move(utility.x, utility.y);
  await browser.mouse.down();
  await browser.mouse.up();
  const editor = screen.getByRole("textbox", /^Comment on lines/);
  await editor.fill("Draft comment");
  await settle();
  await app.screenshot("diff-draft-before-escape");
  await browser.keyboard.press("Escape");
  await editor.waitFor({ state: "hidden" });
  await settle();
  await app.screenshot("diff-after-first-escape");
  const diffKeptOpen = await sheet.isVisible();
  await browser.keyboard.press("Escape");
  await screen.getByRole("dialog", "Workspace panel").waitFor({state:"hidden"});
  await settle();
  await app.screenshot("diff-after-second-escape");
  await screen.getByRole("button", /^Agent Review/).tap();
  await browser.locator('a[href="https://github.com/example/demo/pull/42"]').first().click();
  await screen.getByRole("button", "Code", {exact:true}).tap();
  await screen.getByRole("button", "Expand diff", {exact:true}).tap();

  await screen.getByRole("button", "Reply", {exact:true}).tap();
  const reply = screen.getByRole("textbox", "Reply to this conversation");
  await reply.fill("Draft reply");
  await settle();
  await app.screenshot("review-draft-before-escape");
  await browser.keyboard.press("Escape");
  await reply.waitFor({state:"hidden"});
  await settle();
  await app.screenshot("review-after-first-escape");
  const reviewKeptOpen = await sheet.isVisible();
  await browser.keyboard.press("Escape");
  await sheet.waitFor({state:"hidden"});
  await settle();
  await app.screenshot("review-after-second-escape");
  expect({diffKeptOpen,reviewKeptOpen}).toEqual({diffKeptOpen:true,reviewKeptOpen:true});
});
