import { createHash } from "node:crypto";
import JSZip from "../../apps/web/node_modules/jszip/lib/index.js";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Open VSX collection labels keep whole graphemes", WEB, async ({ t3, app, browser, screen }) => {
  const names = ["A".repeat(47) + "🎨", "A".repeat(46) + "🇺🇸", "e" + "\u0301".repeat(50)];
  const fixtures = await Promise.all(names.map(async (displayName, i) => {
    const name = `fixture-${i}`;
    const manifest = { publisher: "fixture", name, displayName, version: "1.0.0", license: "MIT", contributes: { themes: [
      { label: `Alpha Dark ${i}`, uiTheme: "vs-dark", path: "./alpha.json" },
      { label: `Beta Dark ${i}`, uiTheme: "vs-dark", path: "./beta.json" },
    ] } };
    const zip = new JSZip();
    zip.file("extension/package.json", JSON.stringify(manifest));
    for (const file of ["alpha", "beta"]) zip.file(`extension/${file}.json`, JSON.stringify({ name: file, type: "dark", colors: { "editor.background": "#151515", "editor.foreground": "#eeeeee" }, tokenColors: [] }));
    const bytes = await zip.generateAsync({ type: "uint8array" });
    return { name, manifest, bytes, checksum: createHash("sha256").update(bytes).digest("hex") };
  }));
  await browser.route(/^https:\/\/open-vsx.org\//, async (route) => {
    const path = new URL(route.request.url).pathname;
    if (path === "/api/-/search") return route.fulfill({ json: { extensions: fixtures.map(f => ({ namespace: "fixture", name: f.name })) } });
    const f = fixtures.find(f => path.includes(f.name));
    if (!f) return route.fulfill({ status: 404 });
    if (path.endsWith("/manifest")) return route.fulfill({ json: f.manifest });
    if (path.endsWith("/sha256")) return route.fulfill({ body: f.checksum });
    if (path.endsWith("/download")) return route.fulfill({ body: f.bytes, contentType: "application/zip", headers: { "content-length": String(f.bytes.length) } });
    return route.fulfill({ json: { namespace: "fixture", name: f.name, displayName: f.manifest.displayName, version: "1.0.0", license: "MIT", files: Object.fromEntries(["manifest", "sha256", "download"].map(key => [key, `https://open-vsx.org/api/fixture/${f.name}/${key}`])) } });
  });
  await t3.project("Theme demonstration");
  await t3.open("/settings/appearance");
  for (let i = 0; i < names.length; i++) {
    await screen.getByRole("button", "Add theme", { exact: true }).tap();
    await screen.getByRole("searchbox", "Search Open VSX themes").fill("fixture");
    await screen.getByRole("button", `Install ${names[i]}`, { exact: true }).tap();
    await screen.getByRole("dialog", "Add a theme").waitFor({ state: "hidden" });
  }
  const labels = await browser.evaluate(() => {
    const themes = JSON.parse(localStorage.getItem("t3code:themes:v1") ?? "[]");
    return [...new Set(themes.map((t: { collection?: { label: string } }) => t.collection?.label).filter(Boolean))] as string[];
  });
  for (let i = 0; i < labels.length; i++) {
    await screen.getByRole("button", `Remove themes from ${labels[i]}`, { exact: true }).tap();
    await screen.getByRole("heading", /^Remove themes from/).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
      return null;
    });
    await app.screenshot(["emoji-removal", "flag-removal", "combining-removal"][i]!);
    await screen.getByRole("button", "Cancel", { exact: true }).tap();
  }
  expect(labels).toEqual(["A".repeat(47), "A".repeat(46), "open-vsx:fixture.fixture-2"]);
});
