/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("File and icon pickers retain settled results and an active row", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({colorScheme:"dark"});
  const files: Record<string,string> = {};
  for(let i=0;i<210;i++) files[`src/app-component-${String(i).padStart(3,"0")}.ts`] = "export {};";
  for(const name of ["appv-mark", "app-logo", "app-banner", "app-button", "app-card", "app-cover"]) files[`${name}.svg`] = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" rx="6" fill="#4f86ee"/></svg>';
  const project = await t3.project("picker-demo", files);
  const replayModel = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const snapshot = yield* client["server.refreshProviders"]({instanceId:ProviderInstanceId.make("devReplay"),cwd:project,fresh:true,refreshModels:true});
    const models = snapshot.providers.find(p => p.instanceId === "devReplay")?.models ?? [];
    return models.find(m => m.slug === "multi-turn")?.slug ?? models[0]?.slug ?? "multi-turn";
  }).pipe(Effect.scoped));
  const thread = await t3.thread({project,title:"Search project files",model:replayModel,messages:["Start"]});
  await browser.addInitScript((workspace) => {
    const redactWorkspace = () => {
      const walker = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_TEXT);
      let node;
      while ((node = walker.nextNode())) {
        if(node.parentElement?.closest("script,style")) continue;
        if(node.textContent?.includes(workspace)) node.textContent = node.textContent.replaceAll(workspace, "~/picker-demo");
      }
    };
    new MutationObserver(redactWorkspace).observe(document, {childList:true, subtree:true, characterData:true});
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if(typeof data === "string") {
        const request = JSON.parse(data);
        if(request.tag === "projects.searchEntries" && request.payload?.query?.startsWith("appv")) {
          document.documentElement.dataset.pickerSearch = "pending";
          document.addEventListener("release-picker-search", () => { delete document.documentElement.dataset.pickerSearch; send.call(this,data); }, {once:true});
          return;
        }
      }
      send.call(this,data);
    };
  }, project);
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Search project files", {exact:true}).waitFor();
  const capture = async (label:string) => {
    // Give the browser compositor a stable frame before capturing the retained list.
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 750)); return null; });
    await app.screenshot(label);
  };
  const observations: Array<{picker:string;retained:boolean;active:boolean;guarded:boolean}> = [];
  for(const picker of ["file", "image"]) {
    if(picker === "file") await browser.keyboard.press("Control+p");
    else {
      await t3.open("/settings/projects");
      await screen.getByRole("button", /^picker-demo ~\/picker-demo$/).tap();
      await screen.getByRole("button", "Choose a project icon file", {exact:true}).tap();
    }
    const search = screen.getByPlaceholder(picker === "file" ? "Search files…" : "Search image files…");
    await search.fill("app");
    await screen.getByRole("option", /appv-mark.svg/).waitFor();
    await capture(`${picker}-settled-app`);
    const before = await browser.evaluate(() => [...document.querySelectorAll('[role="option"]')].map(e=>e.textContent));
    await search.fill("appv");
    await browser.locator('html[data-picker-search="pending"]').waitFor({state:"attached"});
    await capture(`${picker}-pending-appv`);
    const retained = await browser.evaluate(() => [...document.querySelectorAll('[role="option"]')].map(e=>e.textContent));
    await browser.evaluate(() => document.dispatchEvent(new Event("release-picker-search")));
    await screen.getByRole("option").first().getByText("appv-mark.svg", {exact:true}).first().waitFor();
    await capture(`${picker}-settled-appv`);
    const active = await browser.evaluate(() => {
      const row = document.querySelector('[role="option"]');
      return !!row && row.getAttribute("class")?.includes("bg-accent");
    });
    // Exercise selection guards after the comparable captures, on another pending query.
    await search.fill("app");
    await screen.getByRole("option", /app-logo.svg/).waitFor();
    await search.fill("appv-m");
    await browser.locator('html[data-picker-search="pending"]').waitFor({state:"attached"});
    await search.press("Enter");
    const row = screen.getByRole("option").first();
    if(retained.length) await row.tap();
    const guarded = await browser.evaluate(() => !!document.querySelector('input[placeholder="Search files…"], input[placeholder="Search image files…"]'));
    await browser.evaluate(() => document.dispatchEvent(new Event("release-picker-search")));
    await screen.getByRole("option", /appv-mark.svg/).waitFor();
    observations.push({picker,retained:JSON.stringify(before)===JSON.stringify(retained),active:!!active,guarded});
    await browser.keyboard.press("Escape");
    if(picker === "file") await browser.keyboard.press("Escape");
  }
  expect(observations).toEqual([
    {picker:"file",retained:true,active:true,guarded:true},
    {picker:"image",retained:true,active:true,guarded:true},
  ]);
});
