/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { execFileSync } from "node:child_process";
import { ProjectSnapshot } from "@t3tools/contracts";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("Canonically equivalent accents keep the loaded Café suggestion", WEB, async ({t3, app, browser, screen}) => {
  const workspace = await t3.project("Accent sample");
  execFileSync("git", ["remote", "add", "origin", "https://gitlab.com/julius54/nfc-proof-46268-a1796065786.git"], {cwd: workspace});
  const thread = await t3.thread({project: workspace, title: "Accent completion", messages: ["Start"], model: "default"});
  const origin = app.baseUrl!;
  const environment = await runPromise(environmentId(origin));
  const project = await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const {projects} = yield* HttpClient.execute(HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
    return projects.find(p => p.workspaceRoot === workspace)!;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  await t3.open(thread);
  await t3.open(`/pull-requests?${new URLSearchParams({repository:"julius54/nfc-proof-46268-a1796065786", number:"1", selectedProjectId:project.id, selectedEnvironmentId:environment, selectedHost:"gitlab.com"})}`);
  await screen.getByRole("button", "Comment on merge request", {exact:true}).tap();
  const composer = screen.getByRole("combobox", "Comment on this merge request", {exact:true});
  await composer.fill("#");
  await screen.getByText("Café fix", {exact:true}).waitFor({timeout:60000});
  await composer.fill("#Café");
  await screen.getByText("Café fix", {exact:true}).waitFor();
  await app.screenshot("precomposed-control");
  await composer.fill("#Caf");
  await screen.getByText("Café fix", {exact:true}).waitFor();
  // Wait for the real host's Caf search to settle before appending the decomposed accent.
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); });
  const kept = await browser.evaluate(async () => {
    const input = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on this merge request"]')!;
    const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;
    setter.call(input, "#Cafe\u0301");
    input.setSelectionRange(6, 6);
    input.dispatchEvent(new Event("input", {bubbles:true}));
    await new Promise(resolve => setTimeout(resolve, 40));
    return [...document.querySelectorAll('[role="option"]')].some(el => el.textContent?.includes("Café fix"));
  });
  await app.screenshot("decomposed-during-local-narrowing");
  // Two-character queries read the real unsearched GitLab page, so the settled popup
  // can also show the local mismatch without the host's separate Unicode search behavior.
  await composer.fill("#é");
  await screen.getByText("Café fix", {exact:true}).waitFor();
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); });
  await app.screenshot("short-precomposed-control");
  await composer.fill("#e\u0301");
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); });
  await app.screenshot("short-decomposed-settled");
  const shortKept = await screen.getByText("Café fix", {exact:true}).isVisible();
  expect(kept, "The loaded Café fix candidate remains visible 40 ms after typing decomposed é, before the 200 ms host search debounce").toBe(true);
  expect(shortKept, "A settled decomposed é query keeps the canonically equivalent accented candidate").toBe(true);
});
