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

test("Connected and fresh clients agree after evicting the oldest of 129 inactive terminals", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  // Hide only project-picker path descriptions in public recordings.
  await browser.addInitScript(() => {
    const install = () => {
      const style = document.createElement("style");
      style.textContent = '[role="dialog"][aria-label="Command palette"] [role="option"] .text-xs { visibility: hidden !important; }';
      document.head.append(style);
    };
    if (document.head) install();
    else document.addEventListener("DOMContentLoaded", install, { once: true });
  });
  for (let n = 1; n <= 129; n++) await t3.project(`p${String(n).padStart(3, "0")}`);
  await t3.open();
  await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  for (let n = 1; n <= 129; n++) {
    const title = `p${String(n).padStart(3, "0")}`;
    await browser.keyboard.press("Control+Shift+o");
    await screen.getByRole("dialog", "Command palette").getByRole("combobox").fill(title);
    await screen.getByRole("option", title, { exact: false }).tap();
    const toggle = screen.getByRole("button", "Toggle terminal drawer");
    await toggle.tap();
    const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
    await input.waitFor();
    await input.focus();
    await browser.keyboard.type("sleep 30; exit\n");
    await toggle.tap();
    await input.waitFor({ state: "hidden" });
  }
  // The reproduction waits for all 129 real shell processes to exit before comparing clients.
  await new Promise(resolve => setTimeout(resolve, 40_000));
  const rows = () => browser.evaluate(() => [...document.querySelectorAll('[data-testid="sidebar-draft-row"]')].map(el => el.getAttribute("aria-label") ?? ""));
  const connected = await rows();
  await browser.evaluate(() => {
    const rows = [...document.querySelectorAll('[data-testid="sidebar-draft-row"]')];
    rows.at(-1)?.scrollIntoView({ block: "end", inline: "nearest" });
    return null;
  });
  await app.screenshot("connected-client-after-eviction");
  await browser.evaluate(() => {
    const frame = document.createElement("iframe");
    frame.id = "fresh-client";
    frame.src = "/";
    frame.style.cssText = "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647";
    document.body.append(frame);
    return null;
  });
  const fresh = browser.frameLocator("#fresh-client");
  await fresh.getByRole("button", "Toggle terminal drawer").waitFor();
  await fresh.getByTestId("sidebar-draft-row").first().waitFor();
  const freshRows = await browser.evaluate(() => [...document.querySelector<HTMLIFrameElement>("#fresh-client")!.contentDocument!.querySelectorAll('[data-testid="sidebar-draft-row"]')].map(el => el.getAttribute("aria-label") ?? ""));
  await browser.evaluate(() => {
    const doc = document.querySelector<HTMLIFrameElement>("#fresh-client")!.contentDocument!;
    const row = [...doc.querySelectorAll('[data-testid="sidebar-draft-row"]')].at(-1);
    let parent = row?.parentElement;
    while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
    if (parent) parent.scrollTop = parent.scrollHeight;
    return null;
  });
  await app.screenshot("fresh-client-after-eviction");
  await browser.evaluate(() => { document.querySelector("#fresh-client")!.remove(); return null; });
  await app.screenshot("connected-client-after-fresh-connects");
  console.log(JSON.stringify({ connectedCount: connected.length, freshCount: freshRows.length, onlyConnected: connected.filter(label => !freshRows.includes(label)), onlyFresh: freshRows.filter(label => !connected.includes(label)) }));
  await expect(connected.length).toBe(128);
  await expect(connected.some(label => /\bp001\b/.test(label))).toBe(false);
  await expect([...connected].sort()).toEqual([...freshRows].sort());
});
