/// <reference lib="dom" />
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

test("Archive keyboard navigation retains focus", WEB, async ({ t3, app, screen, browser }) => {
  const zip = new JSZip();
  zip.file("hello.txt", "Hello from the archive root.");
  zip.file("docs/notes.txt", "Archive notes.");
  zip.file("docs/sub/deep.txt", "Nested document.");
  const project = await t3.project("demo", { "sample.zip": await zip.generateAsync({ type: "nodebuffer" }) });
  const seed = (model: string) => t3.thread({ project, title: "Archive keyboard navigation", messages: ["Start"], model });
  const thread = await seed("multi-turn").catch((error) => {
    if (!String(error).includes("Advertised models: default")) throw error;
    return seed("default").catch((error) => {
      if (!String(error).includes("Advertised models: showcase")) throw error;
      return seed("multi-turn");
    });
  });
  await t3.open(thread);
  await screen.getByRole("button", "Attach files", { exact: true }).waitFor();
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  await screen.getByRole("treeitem", "sample.zip", { exact: true }).tap();
  await screen.getByRole("button", "docs", { exact: true }).waitFor();
  const handle = await browser.evaluate(() => {
    const node = [...document.querySelectorAll<HTMLElement>('[role="separator"]')].find(el => !el.hasAttribute("aria-label") && el.getBoundingClientRect().x > 1000)!;
    const rect = node.getBoundingClientRect();
    return { x: rect.x + 2, y: rect.y + rect.height / 2 };
  });
  await browser.mouse.move(handle.x, handle.y);
  await browser.mouse.down();
  await browser.mouse.move(handle.x - 480, handle.y);
  await browser.mouse.up();
  await browser.mouse.move(700, 500);
  const observations: string[] = [];
  const record = async (label: string) => {
    observations.push(await browser.evaluate(() => {
      const active = document.activeElement;
      if (active?.matches('[aria-label="Parent folder"]')) return "Parent folder";
      if (active?.matches('[aria-label="Back to archive"]')) return "Back to archive";
      if (active?.matches('div[tabindex="-1"]') && active.querySelector("table tbody")) return "Archive list";
      return active?.getAttribute("placeholder") ?? active?.getAttribute("aria-label") ?? active?.tagName ?? "none";
    }));
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 5; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(label);
      const root = resolve(process.cwd(), process.env.PROOF_CAPTURE_ROOT!);
      if (readFileSync(resolve(root, previous)).equals(readFileSync(resolve(root, current)))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const enter = async (name: string) => {
    await browser.evaluate((name) => {
      const button = [...document.querySelectorAll<HTMLButtonElement>("button")].find(b => (b.getAttribute("aria-label") ?? b.textContent?.trim()) === name);
      button!.focus();
    }, name);
    await browser.keyboard.press("Enter");
  };
  await browser.evaluate(() => document.querySelector<HTMLButtonElement>('[aria-label="Save file"]')!.focus());
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "notes.txt", { exact: true }).waitFor();
  await record("01-open-docs");
  await enter("sub");
  await screen.getByRole("button", "deep.txt", { exact: true }).waitFor();
  await record("02-open-sub");
  await enter("Parent folder");
  await screen.getByRole("button", "notes.txt", { exact: true }).waitFor();
  await record("03-parent-to-docs");
  await enter("notes.txt");
  await screen.getByRole("button", "Back to archive").waitFor();
  await screen.getByText("Archive notes.", { exact: true }).waitFor();
  await record("04-open-notes");
  await enter("Back to archive");
  await screen.getByRole("button", "notes.txt", { exact: true }).waitFor();
  await record("05-back-to-docs");
  await enter("Parent folder");
  await screen.getByRole("button", "hello.txt", { exact: true }).waitFor();
  await record("06-parent-to-root");
  await enter("hello.txt");
  await screen.getByRole("button", "Back to archive").waitFor();
  await screen.getByText("Hello from the archive root.", { exact: true }).waitFor();
  await record("07-open-hello");
  await enter("Back to archive");
  await screen.getByRole("button", "hello.txt", { exact: true }).waitFor();
  await record("08-back-to-root");
  expect(observations).toEqual(["Parent folder", "Parent folder", "Parent folder", "Back to archive", "Parent folder", "Archive list", "Back to archive", "Archive list"]);
});
