import { expect } from "e2e";
import JSZip from "jszip";
import { test, WEB } from "./t3.ts";

test("Archive entries with unknown extensions open readable UTF-8 text", WEB, async ({ t3, app, screen, browser }) => {
  const text = "Release 1.2.3\n- Fixed the archive preview\n";
  const archive = await new JSZip()
    .file("CHANGELOG", text)
    .file("NOTICE", "Copyright 2026 Sample\n")
    .file("go.mod", "module example.com/sample\n")
    .file(".npmrc", "save-exact=true\n")
    .file("firmware", new Uint8Array([0, 1, 2, 0, 255]))
    .generateAsync({ type: "uint8array" });
  const project = await t3.project("sample", { "pkg.zip": archive, CHANGELOG: text });
  const thread = await t3.thread({ project, title: "Review archive", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const open = async (name: string) => {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(name);
    await screen.getByRole("option", name, { exact: false }).tap();
  };
  const back = async () => {
    try {
      await screen.getByRole("button", "Back to archive", { exact: true }).tap();
    } catch {
      await screen.getByRole("table", "Archive entries").waitFor();
    }
  };
  await open("CHANGELOG");
  await screen.getByText("Release 1.2.3", { exact: false }).waitFor();
  await app.screenshot("loose-changelog-control");
  await open("pkg.zip");
  await screen.getByRole("button", "firmware", { exact: true }).tap();
  await screen.getByRole("alert").waitFor();
  await app.screenshot("binary-firmware");
  await back();
  for (const name of ["NOTICE", "go.mod", ".npmrc", "CHANGELOG"]) {
    await screen.getByRole("table", "Archive entries").getByRole("button", name, { exact: true }).tap();
    try {
      await browser.locator('[role="alert"], [data-line]').first().waitFor();
    } catch {
      // Cold Vite dependency optimization can reload the page and reset the archive to its list.
      await screen.getByRole("table", "Archive entries").getByRole("button", name, { exact: true }).tap();
      await browser.locator('[role="alert"], [data-line]').first().waitFor();
    }
    await app.screenshot(`archive-${name.replaceAll(".", "-")}`);
    if (name !== "CHANGELOG") await back();
  }
  await expect(screen.getByText("Release 1.2.3", { exact: false })).toBeVisible();
});
