import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("PR behind count uses German app language in an English browser", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Pull request language");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).tap();
  await screen.getByText("Deutsch", { exact: true }).tap();
  await screen.getByLabel("Sprache", { exact: true }).waitFor();
  await t3.open("/pull-requests?repository=pingdotgg%2Ft3code&number=17779&selectedUrl=https%3A%2F%2Fgithub.com%2Fpingdotgg%2Ft3code%2Fpull%2F17779");
  const warning = browser.locator('button[aria-label^="Dieser Branch liegt "]:not([inert] *):visible').first();
  try {
    await warning.waitFor({ timeout: 20000 });
  } catch {
    await screen.getByRole("button", "Pull Requests aktualisieren", { exact: true }).tap();
    await warning.waitFor({ timeout: 60000 });
  }
  await screen.getByText("Pull Requests werden geladen...", { exact: true }).waitFor({ state: "hidden", timeout: 90000 });
  await warning.hover();
  await screen.getByText("Die Änderungen können sauber gemergt werden.", { exact: true }).waitFor();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
  const actual = await browser.evaluate(() => {
    const label = [...document.querySelectorAll("button")].map(b => b.getAttribute("aria-label") ?? "").find(t => /^Dieser Branch liegt [\d,.]+ Commits hinter main\.$/.test(t))!;
    const count = Number(label.match(/[\d,.]+/)![0].replace(/[,.]/g, ""));
    return { label, count, lang: document.documentElement.lang, browser: navigator.language, defaultNumber: (1234).toLocaleString(), popover: document.body.innerText };
  });
  if (actual.browser !== "en-US" || actual.lang !== "de" || actual.defaultNumber !== "1,234" || actual.count < 1000) throw new Error(`Wrong reproduction conditions: ${JSON.stringify(actual)}`);
  await app.screenshot("german-pr-behind-count");
  expect(actual.label).toBe(`Dieser Branch liegt ${new Intl.NumberFormat("de").format(actual.count)} Commits hinter main.`);
  expect(actual.popover).toContain(`Dieser Branch liegt ${new Intl.NumberFormat("de").format(actual.count)} Commits hinter main.`);
});
