/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("An archive created from dot lists its real contents at root and opens nested files", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo", { "src/a.txt": "hi", "README.md": "readme" });
  const archivePath = `${project}/../demo.tgz`;
  execFileSync("tar", ["-C", project, "--exclude=.git", "-czf", archivePath, "."]);
  writeFileSync(`${project}/demo.tgz`, readFileSync(archivePath));
  const thread = await t3.thread({ project, title: "Archive preview", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "demo.tgz").tap();
  await screen.getByRole("table", "Archive entries").waitFor({ state: "visible" });
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("archive-root");
  const rootNames = await browser.evaluate(() => Array.from(document.querySelectorAll('table[aria-label="Archive entries"] tbody button')).map(b => b.textContent?.trim()));
  if (rootNames.includes(".")) await screen.getByRole("button", ".", { exact: true }).tap();
  await screen.getByRole("button", "src", { exact: true }).tap();
  await screen.getByRole("button", "a.txt", { exact: true }).tap();
  await screen.getByText("hi", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("nested-file");
  expect(rootNames).toEqual(["src", "README.md"]);
});
