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

test("An unchanged relative target does not rank an unrelated basename ahead of its importer", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("diff-order", {
    "src/z.ts": "export const z = 1;\n",
    "src/other.ts": "export const other = 1;\n",
    "zzz/z.ts": "export const unrelated = 1;\n",
  });
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  await git("remote", "add", "origin", "https://gitlab.com/julius54/factory-diff-order-44623-evidence-1.git");
  await git("fetch", "origin", "main");
  await git("reset", "--hard", "origin/main");
  const thread = await t3.thread({project, title: "Diff ordering review", messages: ["first"]});
  await browser.setViewport({width: 1440, height: 1000});
  await t3.open(thread);
  await t3.open("/pull-requests");
  await screen.getByRole("button", /Open #1 Relative import with unchanged target/).tap();
  await screen.getByRole("button", "Code", {exact: true}).tap();
  await screen.getByRole("button", "Maximize panel", {exact: true}).tap();
  await browser.locator('[data-viewed-toggle]').first().waitFor();
  await app.screenshot("relative-import-file-order");
  const paths = await browser.evaluate(() => {
    const found: string[] = [];
    const walk = (root: Document | ShadowRoot | Element) => {
      for (const element of root.querySelectorAll("*")) {
        if (element.hasAttribute("data-diffs-header")) {
          const title = element.querySelector("[data-title]")?.textContent?.trim();
          if (title) found.push(title);
        }
        if (element.shadowRoot) walk(element.shadowRoot);
      }
    };
    walk(document);
    return found;
  });
  expect(paths, "The unchanged src/z.ts must not make zzz/z.ts a dependency of src/a.ts").toEqual(["src/a.ts", "zzz/z.ts"]);
});
