/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";

import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts";

test(
  "A padded labeled thread link becomes a clean chip",
  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((provider) => provider.instanceId === "devReplay" && provider.models.some(({ slug }) => slug === "multi-turn"));
        }),
        Stream.runHead,
      );
    }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
    const source = await t3.thread({ project, title: "Target", messages: ["Message"] });
    const target = await t3.thread({ project, title: "Composer", messages: ["Draft"] });
    const environment = await runPromise(environmentId(app.baseUrl ?? ""));
    const href = `https://app.t3.codes/threads/${environment}/${encodeURIComponent(source.threadId)}`;

    await t3.open(target);
    const composer = screen.getByRole("textbox");
    const custom = `t3-thread://v2/${environment}/${source.threadId}`;
    const results: Array<{ label: string; clean: boolean }> = [];
    const destinations = [href, `<${href}>`, custom, `<${custom}>`];
    for (const [paddingName, padding] of [["control", ""], ["space", " "], ["tab", "\t"], ["LF", "\n"], ["CRLF", "\r\n"]]) {
      for (const [index, destination] of destinations.entries()) {
        const label = `${paddingName}-${["hosted", "angle-hosted", "custom", "angle-custom"][index]}`;
        await composer.tap();
        await browser.keyboard.press("ControlOrMeta+a");
        await browser.keyboard.press("Backspace");
        await browser.evaluate((text) => {
          const editor = document.activeElement;
          if (!(editor instanceof HTMLElement) || !editor.isContentEditable) throw new Error("Composer is not focused");
          const clipboardData = new DataTransfer();
          clipboardData.setData("text/plain", text);
          editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
          return null;
        }, `[Target](${padding}${destination}${padding})`);
        await app.screenshot(label);
        const result = await browser.evaluate(() => {
          const editor = document.querySelector('[data-testid="composer-editor"]')?.cloneNode(true);
          if (!(editor instanceof HTMLElement)) return false;
          const chips = editor.querySelectorAll('[aria-label="Thread, Target"]');
          if (chips.length !== 1) return false;
          chips[0]!.replaceWith("Target");
          return editor.textContent?.trim() === "Target";
        });
        results.push({ label, clean: result });
      }
    }
    for (const side of ["before", "after"]) {
      await composer.tap();
      await browser.keyboard.press("ControlOrMeta+a");
      await browser.keyboard.press("Backspace");
      await browser.evaluate((text) => {
        const editor = document.activeElement!;
        const clipboardData = new DataTransfer();
        clipboardData.setData("text/plain", text);
        editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
        return null;
      }, `[Target](${side === "before" ? "\n \t\n" : ""}${href}${side === "after" ? "\n \t\n" : ""})`);
      await app.screenshot(`blank-line-${side}`);
    }
    expect(results.filter((result) => !result.clean)).toEqual([]);
  },
);
