import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Saved environment route count follows German language", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  await t3.thread({ project, title: "Example", messages: ["Start"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await t3.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    await screen.getByRole("button", "Add environment", { exact: true }).tap();
    let dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment", { exact: true }).tap();
    await screen.getByRole("button", "Routes", { exact: true }).tap();
    await screen.getByRole("button", "Add route", { exact: true }).tap();
    const minted = await runPromise(makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]));
    dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host.replace("127.0.0.1", "localhost"));
    await dialog.getByPlaceholder("PAIRCODE").fill(JSON.parse(minted.stdout).credential);
    await dialog.getByRole("button", "Add route", { exact: true }).tap();
    await screen.getByRole("button", "2 routes", { exact: true }).tap();
    await screen.getByRole("button", "General", { exact: true }).tap();
    await screen.getByLabel("Language", { exact: true }).tap();
    await screen.getByText("Deutsch", { exact: true }).tap();
    await screen.getByLabel("Sprache", { exact: true }).waitFor();
    await screen.getByRole("button", "Umgebungen", { exact: true }).tap();
    await screen.getByRole("button", "Liste", { exact: true }).tap();
    await screen.getByRole("button", /^(2 routes|2 Routen)$/).waitFor();
    await browser.evaluate(() => {
      for (const button of document.querySelectorAll<HTMLButtonElement>('[data-slot="toast-close"]')) button.click();
    });
    await browser.locator('[data-slot="toast-close"]').first().waitFor({ state: "hidden" });
    await app.screenshot("german-saved-environment-two-routes");
    await expect(screen.getByRole("button", "2 Routen", { exact: true })).toBeVisible();
  } finally {
    await server.stop();
  }
});
