/// <reference lib="dom" />
import { CommandId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Polish snooze uses one name throughout the sidebar and custom dialog", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter((event) => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some((p) => p.instanceId === "devReplay" && p.models?.some((m) => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("45 seconds")));
  await browser.setViewport({ width: 1440, height: 900 });
  const alpha = await t3.thread({ project, title: "watek alpha", messages: ["Start"] });
  const beta = await t3.thread({ project, title: "watek beta", messages: ["Start"] });
  const extra = [];
  for (const title of ["watek gamma", "watek delta", "watek epsilon", "watek zeta", "watek eta", "watek theta", "watek iota", "watek kappa", "watek lambda"]) {
    extra.push(await t3.thread({ project, title, messages: ["Start"] }));
  }
  const [gamma, delta, epsilon, zeta, eta, theta, iota, kappa, lambda] = extra;
  const remove = async (ids: string[]) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    for (const id of ids) yield* client["orchestration.dispatchCommand"]({ type: "thread.delete", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(id) });
  }).pipe(Effect.scoped));
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).tap();
  await screen.getByText("Polski", { exact: true }).tap();
  await screen.getByLabel("Język", { exact: true }).waitFor();
  await t3.open(alpha);
  const capture = async (label: string) => {
    await screen.getByText("Synchronizowanie wiadomości...", { exact: true }).waitFor({ state: "hidden" });
    await browser.evaluate(async () => {
      await Promise.allSettled(document.getAnimations().filter((a) => a.effect?.getTiming().iterations !== Infinity).map((a) => a.finished));
      return null;
    });
    await app.screenshot(label);
  };
  const observed: string[] = [];
  const remember = async () => observed.push(await browser.evaluate(() => document.body.innerText));
  await browser.locator(`[data-thread-item$="${beta.threadId}"]`).waitFor();
  await browser.evaluate((id: string) => {
    const row = document.querySelector(`[data-sidebar-row$="${id}"]`)!;
    const rect = row.getBoundingClientRect();
    row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: rect.x + 80, clientY: rect.y + 15 }));
    return null;
  }, beta.threadId);
  const snoozeMenu = screen.getByRole("menuitem", /^(Odrocz|Uśpij)$/);
  await snoozeMenu.waitFor();
  await capture("single-thread-menu");
  await remember();
  await snoozeMenu.tap();
  await screen.getByRole("menuitem", "Niestandardowe…", { exact: true }).tap();
  await screen.getByRole("dialog").waitFor();
  await screen.getByLabel("Godzina", { exact: true }).fill("23:00");
  await capture("custom-date-dialog");
  await remember();
  await screen.getByLabel("Data", { exact: true }).tap();
  await browser.locator('[data-slot="popover-popup"]').waitFor();
  const calendarLabel = await browser.evaluate(() => document.querySelector('[data-slot="popover-popup"]')?.getAttribute("aria-label"));
  await capture("choose-snooze-date");
  await browser.keyboard.press("Escape");
  await screen.getByRole("button", "Czas trwania", { exact: true }).tap();
  await capture("custom-duration-dialog");
  await remember();
  await screen.getByRole("dialog").getByRole("button", /^(Odrocz|Uśpij)$/).tap();
  await screen.getByRole("button", /^(Odroczone|Uśpione)/).waitFor();
  await capture("snoozed-section-and-notification");
  await remember();
  const announcement = async (pattern: string) => browser.evaluate(async (pattern: string) => {
    const find = () => Array.from(document.querySelectorAll('[aria-live="polite"]'), (region) => region.textContent ?? "").find((text) => new RegExp(pattern).test(text));
    const existing = find();
    if (existing) return existing;
    return new Promise<string>((resolve) => {
      const observer = new MutationObserver(() => { const text = find(); if (text) { observer.disconnect(); resolve(text); } });
      observer.observe(document.body, { subtree: true, childList: true, characterData: true });
    });
  }, pattern);
  const snoozedAnnouncement = await announcement("(Odroczono|Uśpiono) 1 wątek");
  await browser.keyboard.press("Control+z");
  const undoAnnouncement = await announcement("Cofnięto (odroczenie|uśpienie) 1 wątku");
  await browser.locator(`[data-thread-item$="${beta.threadId}"]`).waitFor();
  const context = async (id: string) => browser.evaluate((id: string) => {
    const row = document.querySelector(`[data-sidebar-row$="${id}"]`)!;
    const rect = row.getBoundingClientRect();
    row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: rect.x + 80, clientY: rect.y + 15 }));
    return null;
  }, id);
  const select = async (id: string) => browser.evaluate((id: string) => {
    document.querySelector(`[data-sidebar-row$="${id}"]`)!.dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true }));
    return null;
  }, id);
  const bulk = async (label: string, open: { threadId: string }, others: { threadId: string }[], deleted: { threadId: string }[], failed: number | null) => {
    await t3.open(open);
    await browser.locator(`[data-sidebar-row$="${open.threadId}"]`).waitFor();
    for (const other of others) await select(other.threadId);
    await context(open.threadId);
    const menu = screen.getByRole("menuitem", /^(Odrocz|Uśpij) \([0-9]+\)$/);
    await menu.waitFor();
    await capture(`${label}-bulk-menu`);
    await remember();
    await menu.tap();
    await screen.getByRole("menuitem", "Niestandardowe…", { exact: true }).tap();
    await screen.getByRole("dialog").waitFor();
    await screen.getByRole("button", "Czas trwania", { exact: true }).tap();
    await remove(deleted.map((t) => t.threadId));
    for (const thread of deleted) await browser.locator(`[data-thread-item$="${thread.threadId}"]`).waitFor({ state: "detached" });
    await screen.getByRole("dialog").getByRole("button", /^(Odrocz|Uśpij)$/).tap();
    await screen.getByText(failed === null ? /^Nie udało się (odroczyć|uśpić) wątków$/ : new RegExp(`^Nie udało się (odroczyć|uśpić) ${failed} `)).waitFor();
    await capture(`${label}-failure`);
    await remember();
  };
  await bulk("one", alpha, [beta, gamma!], [beta], 1);
  await bulk("few", delta!, [epsilon!, zeta!], [epsilon!, zeta!], 2);
  await bulk("all", eta!, [theta!], [eta!, theta!], null);
  await t3.open(iota!);
  await browser.locator(`[data-sidebar-row$="${iota!.threadId}"]`).waitFor();
  await context(iota!.threadId);
  await screen.getByRole("menuitem", /^(Odrocz|Uśpij)$/).tap();
  await screen.getByRole("menuitem", "Niestandardowe…", { exact: true }).tap();
  await screen.getByRole("dialog").waitFor();
  await screen.getByRole("button", "Czas trwania", { exact: true }).tap();
  await remove([iota!.threadId]);
  await browser.locator(`[data-thread-item$="${iota!.threadId}"]`).waitFor({ state: "detached" });
  await screen.getByRole("dialog").getByRole("button", /^(Odrocz|Uśpij)$/).tap();
  await screen.getByText(/^Nie udało się (odroczyć|uśpić) wątku$/).waitFor();
  await capture("single-thread-failure");
  await remember();
  await t3.open(kappa!);
  await browser.locator(`[data-sidebar-row$="${kappa!.threadId}"]`).waitFor();
  const deadline = new Date(Math.ceil((Date.now() + 15_000) / 60_000) * 60_000);
  const time = `${String(deadline.getHours()).padStart(2, "0")}:${String(deadline.getMinutes()).padStart(2, "0")}`;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["server.updateSettings"]({ patch: { snoozePresets: [{ kind: "at", day: "today", time }] } });
  }).pipe(Effect.scoped));
  await context(kappa!.threadId);
  await screen.getByRole("menuitem", /^(Odrocz|Uśpij)$/).tap();
  const preset = screen.getByRole("menuitem", /^Dziś wieczorem/);
  await preset.waitFor();
  // This branch requires a real preset to expire while its menu remains open.
  await new Promise((resolve) => setTimeout(resolve, Math.max(0, deadline.getTime() - Date.now() + 1000)));
  await preset.tap();
  await screen.getByText(/^Ten czas (odroczenia|uśpienia) już minął/).waitFor();
  await capture("expired-preset-error");
  await remember();

  await t3.open(lambda!);
  await browser.locator(`[data-sidebar-row$="${lambda!.threadId}"]`).waitFor();
  await context(lambda!.threadId);
  await screen.getByRole("menuitem", /^(Odrocz|Uśpij)$/).tap();
  await screen.getByRole("menuitem", "Niestandardowe…", { exact: true }).tap();
  await screen.getByRole("dialog").waitFor();
  await screen.getByRole("button", "Czas trwania", { exact: true }).tap();
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["orchestration.dispatchCommand"]({ type: "thread.runtime-mode.set", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(lambda!.threadId), runtimeMode: "approval-required" });
    yield* client["orchestration.dispatchCommand"]({ type: "thread.model-selection.set", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(lambda!.threadId), modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "approval" } });
  }).pipe(Effect.scoped));
  await runPromise(makeState(T3_HOME).cli(["thread", "send", lambda!.threadId, "Request an edit", "--wait", "--json"], [2]));
  await screen.getByRole("dialog").getByRole("button", /^(Odrocz|Uśpij)$/).tap();
  await screen.getByText(/^Ten wątek czeka na Ciebie/).waitFor();
  await capture("pending-request-blocks-snooze");
  await remember();
  const sha = execFileSync("git", ["-C", APP_DIR, "rev-parse", "HEAD"], { encoding: "utf8" }).trim();
  writeFileSync(`.e2e/accessibility-${sha}.json`, JSON.stringify({ commit: sha, calendarLabel, snoozedAnnouncement, undoAnnouncement }, null, 2));
  observed.push(snoozedAnnouncement, undoAnnouncement);
  expect(observed.join("\n")).not.toMatch(/Odrocz|odrocz/);
  expect(observed.join("\n")).toContain("Nie udało się uśpić 1 wątku");
  expect(observed.join("\n")).toContain("Nie udało się uśpić 2 wątków");
  expect(calendarLabel).toBe("Wybierz datę uśpienia");
});
