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

test("Modified map chords preserve focus, selection and browser defaults", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("keyboard-demo");
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await browser.emulateMedia({ colorScheme: "dark" });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "Map", { exact: true }).tap();
    await screen.getByRole("button", "This browser", { exact: true }).waitFor();
    await screen.getByRole("button", "Add environment").tap();
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Tab");
    const start = await browser.evaluate(() => {
      const nodes = [...document.querySelectorAll<HTMLElement>("[data-fleet-node]")];
      const client = nodes.find(n => n.getAttribute("aria-label") === "This browser");
      if (!client || nodes.length < 3) throw new Error("Need browser and two real machines");
      client.focus();
      client.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }));
      return (document.activeElement as HTMLElement).dataset.fleetNode;
    });
    const results = [];
    for (const chord of [
      { key: " ", ctrlKey: true },
      { key: "ArrowDown", altKey: true },
      { key: "ArrowLeft", altKey: true },
      { key: "ArrowRight", altKey: true },
      { key: "ArrowDown", ctrlKey: true },
      { key: "ArrowUp", metaKey: true },
      { key: " ", altKey: true },
    ]) {
      results.push(await browser.evaluate(({ chord, start }) => {
        const node = document.activeElement as HTMLElement;
        const before = node.getAttribute("aria-label");
        const event = new KeyboardEvent("keydown", { ...chord, bubbles: true, cancelable: true });
        node.dispatchEvent(event);
        return { chord, prevented: event.defaultPrevented, sameFocus: document.activeElement === node, before };
      }, { chord, start }));
      await app.screenshot(`chord-${results.length}`);
    }
    const selectedAfterModified = await browser.evaluate(() => [...document.querySelectorAll("[data-fleet-node]")].filter(n => n.getAttribute("aria-label")?.endsWith(", selected")).length);
    const controls = await browser.evaluate((start) => {
      const node = document.querySelector<HTMLElement>(`[data-fleet-node="${start}"]`)!;
      node.focus();
      const space = new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true });
      node.dispatchEvent(space);
      const arrow = new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true, cancelable: true });
      node.dispatchEvent(arrow);
      return { spacePrevented: space.defaultPrevented, arrowPrevented: arrow.defaultPrevented, moved: document.activeElement !== node };
    }, start);
    await app.screenshot("plain-controls");
    expect({ results: results.map(({ prevented, sameFocus }) => ({ prevented, sameFocus })), selectedAfterModified, controls }).toEqual({ results: results.map(() => ({ prevented: false, sameFocus: true })), selectedAfterModified: 0, controls: { spacePrevented: true, arrowPrevented: true, moved: true } });
  } finally { await server.stop(); }
});
