/// <reference lib="dom" />
import { expect } from "e2e";
import { writeFile, symlink } from "node:fs/promises";
import { dirname, join } from "node:path";
import { test, WEB } from "./t3.ts";

test("Read-only workspace files keep panel focus on a visible control", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("focus-demo", { "normal.txt": "Ordinary editable workspace file.\n" });
  const outside = join(dirname(project), "outside.txt");
  await writeFile(outside, "Read-only linked source file.\nKeyboard focus should stay visible.\n");
  await symlink(outside, join(project, "link.txt"));
  const thread = await t3.thread({ project, title: "File focus", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openRow = async (name: string) => {
    await expect.poll(() => browser.evaluate((name) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${name}"]`);
        if (row) { row.click(); return true; }
      }
      return false;
    }, name)).toBe(true);
  };
  await browser.locator("[data-right-panel-surface-content]").waitFor();
  await openRow("normal.txt");
  await browser.locator("[data-file-content-focus]").waitFor({ state: "attached" });
  await openRow("link.txt");
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      if (host.shadowRoot?.textContent?.includes("Read-only linked source file.")) return true;
    }
    return false;
  })).toBe(true);
  await browser.mouse.move(750, 600);
  await browser.keyboard.press("F6");
  await browser.keyboard.press("Shift+F6");
  await browser.locator('[data-slot="tooltip-popup"]').waitFor({ state: "hidden" });
  await app.screenshot("read-only-focus-return");
  await browser.keyboard.press("Control+a");
  await app.screenshot("read-only-select-all");
  const focus = await browser.evaluate(() => {
    const el = document.activeElement as HTMLElement;
    const rect = el.getBoundingClientRect();
    return { visible: rect.width > 4 && rect.height > 4, selectedApp: (window.getSelection()?.toString().length ?? 0) > 100, tag: el.tagName, label: el.getAttribute("aria-label"), placeholder: el.getAttribute("placeholder") };
  });
  expect(focus.visible && !focus.selectedApp).toBe(true);
});
