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

test("A bare anchor between nested HTML links leaves the following file independent", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("link-review", { "checklist.ts": "export const ready = true;\n", "review.md": "" });
  const alias = "/tmp/factory-pr-48861-evidence-1/proj";
  await unlink(alias).catch(() => {});
  await symlink(project, alias);
  await writeFile(`${project}/review.md`, `See <a href="https://example.com/outer">outer <a><a href="https://example.com/inner">inner</a> ${alias}/checklist.ts`);
  const thread = await t3.thread({ project, title: "Review links", messages: ["Review the project files."] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openFile = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="review.md"]');
      if (row) { row.click(); return true; }
    }
    return false;
  });
  // Wait for the tree to load; this is navigation, before the bug assertions.
  await expect.poll(openFile).toBe(true);
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("link", "inner", { exact: true }).waitFor();
  await app.screenshot("nested-html-link-followed-by-file");
  await expect.poll(() => browser.evaluate(() => {
    const inner = document.querySelector('a[href="https://example.com/inner"]');
    return {
      nested: !!inner?.parentElement?.closest("a"),
      fileChip: [...document.querySelectorAll('[data-slot="context-chip"]')].some(el => el.textContent?.includes("checklist.ts")),
      literalPlaceholder: inner?.closest("p")?.textContent?.includes("<a>") ?? false,
    };
  })).toEqual({ nested: false, fileChip: true, literalPlaceholder: true });
});
