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

test("Ctrl+W closes the active Issues tab and clears the last selection", WEB, async ({t3, app, browser, screen}) => {
  await t3.project("shortcut-demo");
  await browser.setViewport({width:1280,height:800});
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const r = typeof data === "string" ? JSON.parse(data) : null;
      if (r?._tag !== "Request" || !["issues.list", "issues.detail"].includes(r.tag)) return send.call(this,data);
      const entry = (key: string) => ({
        projectId:"demo", projectTitle:"shortcut-demo",tracker:"github",host:"github.com",scope:"example/demo",key,displayKey:"#"+key,
        title:key === "42418" ? "First issue for shortcut verification" : "Second issue for shortcut verification",
        url:"https://github.com/example/demo/issues/"+key, author:null,state:{category:"open",name:"Open"},createdAt:"2026-11-01T00:00:00.000Z",updatedAt:"2026-11-01T00:00:00.000Z",closedAt:null,assignees:[],labels:[],commentCount:0,
      });
      const value = r.tag === "issues.list" ? {
        entries:[entry("42418"),entry("38102")],errors:[],nextCursors:{},viewers:{},
        trackers:[{tracker:"github",host:"github.com",projectCount:1,capabilities:null,configured:true,detail:null}],
      } : {...entry(String(r.payload.key)), ...r.payload, body:"Synthetic issue used to verify the close-tab keyboard shortcut.",writable:false,
        capabilities:{create:false,edit:false,comment:false,labels:false,assignees:false,reactions:false,templates:false,linkedPullRequests:false,events:false,search:true},
        viewerPermissions:{setState:false,comment:false,edit:false,labels:false,assignees:false},states:[],viewer:null,comments:[],commentsCursor:null,events:[],linkedPullRequests:[]};
      queueMicrotask(() => this.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({_tag:"Exit",requestId:r.id,exit:{_tag:"Success",value}})})));
    };
  });
  await t3.open("/issues");
  await screen.getByRole("button", /#42418 First issue/).waitFor({timeout:60000});
  await screen.getByRole("button", /#42418 First issue/).tap();
  await screen.getByRole("button", "Refresh issue", {exact:true}).waitFor();
  await screen.getByRole("button", /#38102 Second issue/).tap();
  await browser.locator('[data-active-tab="true"]').getByText("#38102",{exact:true}).waitFor();
  await app.screenshot("two-issue-tabs-before-shortcut");
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); return null; });
  await browser.keyboard.press("Control+w");
  await app.screenshot("after-first-close-shortcut");
  const firstSelection = await browser.evaluate(() => new URL(location.href).searchParams.get("key"));
  await browser.keyboard.press("Control+w");
  await app.screenshot("after-last-close-shortcut");
  const lastSelection = await browser.evaluate(() => new URL(location.href).searchParams.get("key"));
  expect(firstSelection, "Closing active #38102 selects remaining #42418").toBe('"42418"');
  expect(lastSelection, "Closing final tab clears the URL selection").toBe(null);
});
