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

test("Copied issue errors end with a complete Unicode code point", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  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" || !["issues.detail", "issues.candidates", "issues.update"].includes(request.tag)) return send.call(this, data);
      const reply = (exit: unknown) => queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {data: JSON.stringify({_tag:"Exit", requestId: request.id, exit})})));
      if (request.tag === "issues.update") {
        const prefix = "Issue operation update failed: ";
        const detail = "A synthetic tracker error ".padEnd(318 - prefix.length - 2, "x") + "re😀 additional diagnostic text".repeat(8);
        reply({_tag:"Failure", cause:[{_tag:"Fail", error:{_tag:"IssueOperationError",operation:"update",detail}}]});
        return;
      }
      if (request.tag === "issues.candidates") {
        reply({_tag:"Success",value:{labels:[{name:"bug",color:"d73a4a",description:"Bug"}],assignees:[],truncated:false}});
        return;
      }
        const { projectId, tracker, scope, key } = request.payload;
        const detail: IssueDetail = {
          projectId,
          tracker,
          scope,
          key,
          host: "github.com",
          displayKey: "#42",
          projectTitle: "demo",
          title: "Unicode error copy",
          body: "The details from the last successful read.",
          url: "https://github.com/example/demo/issues/42",
          author: null,
          state: { category: "open", name: "Open" },
          createdAt: "2026-10-01T00:00:00.000Z",
          updatedAt: "2026-10-01T00:00:00.000Z",
          closedAt: null,
          assignees: [],
          labels: [],
          commentCount: 0,
          writable: true,
          capabilities: {
            create: false,
            edit: false,
            comment: false,
            labels: true,
            assignees: false,
            reactions: false,
            templates: false,
            linkedPullRequests: false,
            events: false,
            search: true,
          },
          viewerPermissions: {
            setState: false,
            comment: false,
            edit: false,
            labels: true,
            assignees: false,
          },
          states: [],
          viewer: null,
          comments: [],
          commentsCursor: null,
          events: [],
          linkedPullRequests: [],
        };

      reply({_tag:"Success",value:detail});
    };
  });
  await t3.open("/issues?selectedProjectId=demo&tracker=github&scope=example/demo&key=42");
  await screen.getByText("Unicode error copy", {exact:true}).waitFor({timeout:60000});
  await screen.getByRole("combobox", "Change labels", {exact:true}).tap();
  await screen.getByRole("option", "bug", {exact:false}).tap();
  await browser.keyboard.press("Escape");
  await screen.getByText("Could not change labels", {exact:true}).waitFor();
  await screen.getByRole("button", "Copy error", {exact:true}).tap();
  await screen.getByRole("button", "Copied error", {exact:true}).waitFor();
  const search = screen.getByRole("searchbox", "Search issues", {exact:true});
  await search.tap();
  await browser.keyboard.press("ControlOrMeta+V");
  await browser.keyboard.press("End");
  await browser.locator('svg[aria-label="Loading"]').waitFor({state:"hidden"});
  await app.screenshot("copied-error-pasted-in-search");
  const pasted = await browser.evaluate(() => (document.querySelector('input[placeholder="Search issues"]') as HTMLInputElement)?.value ?? "");
  expect(pasted).toBe("Issue operation update failed: " + "A synthetic tracker error ".padEnd(318 - "Issue operation update failed: ".length - 2, "x") + "re…");
});
