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

test("Issue filter search applies to loaded and off-page selections", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Filter search demo");
  const sha = (await runPromise(run("git", ["rev-parse", "HEAD"], { cwd: APP_DIR }))).stdout.trim();
  await browser.addInitScript((commit) => {
    document.addEventListener("DOMContentLoaded", () => {
      const marker = document.createElement("div");
      marker.textContent = `App commit ${commit.slice(0, 10)} · synthetic tracker data`;
      marker.style.cssText = "position:fixed;bottom:10px;left:280px;z-index:2147483647;background:#fff;color:#111;padding:8px 12px;border:2px solid #555;font:14px monospace;pointer-events:none";
      document.body.append(marker);
    });
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const req = typeof data === "string" ? JSON.parse(data) : null;
      if (req?._tag !== "Request" || !["issues.list", "issues.candidates"].includes(req.tag)) return send.call(this, data);
      const value = req.tag === "issues.candidates" ? {
        labels: [{ name:"bug", color:"d73a4a", description:"Defect" }, { name:"docs", color:"0075ca", description:"Documentation" }],
        assignees: [{ id:"alice", login:"alice", name:"Alice Example", avatarUrl:null }, { id:"bob", login:"bob", name:"Bob Example", avatarUrl:null }], truncated:true,
      } : {
        entries:[], errors:[], nextCursors:{}, viewers:{},
        scopes:[{ projectId:"demo", tracker:"github", host:"github.com", scope:"example/demo" }],
        trackers:[{ tracker:"github", host:"github.com", projectCount:1, capabilities:{ create:false, edit:false, comment:false, labels:true, assignees:true, reactions:false, templates:false, linkedPullRequests:false, events:false, search:true }, configured:true, detail:null }],
      };
      queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", {data: JSON.stringify({_tag:"Exit",requestId:req.id,exit:{_tag:"Success",value}})})));
    };
  }, sha);
  const failures: string[] = [];
  for (const phase of [
    {kind:"label", value:"bug", missing:false},
    {kind:"assignee", value:"alice", missing:false},
    {kind:"label", value:"off-page-label", missing:true},
    {kind:"assignee", value:"offpage-person", missing:true},
  ]) {
    await t3.open(`/issues?${phase.kind}=${phase.value}`);
    await screen.getByRole("button", /^Filters/).waitFor({timeout:60000});
    await screen.getByRole("button", /^Filters/).tap();
    await screen.getByRole("menuitem", phase.kind === "label" ? /^Labels/ : /^Assignee/).tap();
    const input = screen.getByRole("textbox", phase.kind === "label" ? "Search labels" : "Search people");
    await input.waitFor();
    await screen.getByText(phase.kind === "label" ? "More labels exist than are listed here." : "More people exist than are listed here.", {exact:true}).waitFor();
    await app.screenshot(`${phase.kind}-${phase.missing ? "off-page" : "known"}-clear-before`);
    await input.fill(phase.kind === "label" ? "docs" : "bob");
    await app.screenshot(`${phase.kind}-${phase.missing ? "off-page" : "known"}-nonmatching-search`);
    const result = await browser.evaluate((p) => {
      const role = p.kind === "label" ? "menuitemcheckbox" : "menuitemradio";
      return Array.from(document.querySelectorAll(`[role="${role}"]`)).map(e => e.textContent ?? "");
    }, phase);
    if (result.some(t => t.includes(phase.value))) failures.push(`${phase.kind} ${phase.value} remained during unrelated search`);
    if (phase.kind === "label") {
      await input.fill("zzzz");
      await app.screenshot(`label-${phase.missing ? "off-page" : "known"}-empty-search`);
      const empty = await browser.evaluate(() => document.body.innerText.includes("No labels found"));
      if (!empty) failures.push(`${phase.value} suppressed empty state`);
    }
    await input.fill(phase.value);
    await app.screenshot(`${phase.kind}-${phase.missing ? "off-page" : "known"}-matching-search`);
    await input.fill("");
    await app.screenshot(`${phase.kind}-${phase.missing ? "off-page" : "known"}-clear-restores-selection`);
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
  }
  await expect(failures).toEqual([]);
});
