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

test("Theme search download labels follow the UI language and singular rules", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  await browser.addInitScript(() => {
    const original = window.fetch.bind(window);
    window.fetch = async (...args) => {
      const response = await original(...args);
      const url = String(args[0]);
      if (sessionStorage.getItem("singular-downloads") === "yes" && url.startsWith("https://open-vsx.org/api/") && !url.includes("/file/") && response.ok) {
        const data = await response.clone().json().catch(() => null);
        if (data && typeof data.downloadCount === "number") {
          data.downloadCount = 1;
          return new Response(JSON.stringify(data), { status: response.status, headers: { "content-type": "application/json" } });
        }
      }
      return response;
    };
  });
  await t3.open("/settings/general");
  await screen.getByRole("combobox", "Language", { exact: true }).tap();
  await screen.getByRole("option", "Deutsch", { exact: true }).tap();
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Design hinzufügen", { exact: true }).tap();
  await screen.getByRole("button", "Dracula", { exact: true }).tap();
  await screen.getByRole("article").first().waitFor({ timeout: 60000 });
  const plural = await browser.evaluate(() => Array.from(document.querySelectorAll("article h4 + p")).map(p => p.textContent));
  await app.screenshot("german-live-dracula-downloads");
  await browser.evaluate(() => sessionStorage.setItem("singular-downloads", "yes"));
  await screen.getByRole("button", "Nord", { exact: true }).tap();
  await screen.getByRole("heading", "Nord", { exact: true }).waitFor({ timeout: 60000 });
  const german = await browser.evaluate(() => Array.from(document.querySelectorAll("article h4 + p")).map(p => p.textContent));
  await app.screenshot("german-singular-nord-download");
  await t3.open("/settings/general");
  await screen.getByRole("combobox", "Sprache", { exact: true }).tap();
  await screen.getByRole("option", "English", { exact: true }).tap();
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Add theme", { exact: true }).tap();
  await screen.getByRole("button", "Nord", { exact: true }).tap();
  await screen.getByRole("heading", "Nord", { exact: true }).waitFor({ timeout: 60000 });
  const english = await browser.evaluate(() => Array.from(document.querySelectorAll("article h4 + p")).map(p => p.textContent));
  await app.screenshot("english-singular-nord-download");
  expect({ plural: plural.every(p => / Downloads$/.test(p ?? "")), german: german.every(p => / · 1 Download$/.test(p ?? "")), english: english.every(p => / · 1 download$/.test(p ?? "")) }).toEqual({ plural: true, german: true, english: true });
});
