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

test("Retrying a failed PDF keeps keyboard focus in its preview", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("proj", {"broken.pdf": "%PDF-1.7\nnot a real PDF\n"});
  const thread = await t3.thread({project, title: "PDF retry", messages: ["Start"], model: "default"});
  await browser.setViewport({width: 1440, height: 900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByRole("button", "Files F", {exact:true}).tap();
  await screen.getByRole("treeitem", "broken.pdf", {exact:true}).tap();
  await screen.getByRole("button", "Try again", {exact:true}).waitFor();
  for (let i = 0; i < 80; i++) {
    if (await browser.evaluate(() => document.activeElement?.textContent?.trim() === "Try again")) break;
    await browser.keyboard.press("Tab");
  }
  await browser.locator('button:focus').filter({hasText:"Try again"}).waitFor();
  await browser.locator('[data-slot="tooltip-content"]').waitFor({state:"hidden"});
  await app.screenshot("retry-button-keyboard-focus");
  const before = await browser.evaluate(() => ({x: window.scrollX, y: window.scrollY}));
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Try again", {exact:true}).waitFor();
  await app.screenshot("after-keyboard-retry");
  const result = await browser.evaluate(() => ({
    inPdf: !!document.activeElement?.closest('[role="region"][aria-label="broken.pdf"]'),
    x: window.scrollX, y: window.scrollY,
  }));
  expect(result).toEqual({inPdf:true, ...before});
});
