/// <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 { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Copying a rendered explicit URL preserves its final period", 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(model => model.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Punctuated link", messages: ["Explicit: [https://T3.CODES/docs.](https://t3.codes/docs.)"] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Explicit/).tap();
  await screen.getByText("Explicit: https://T3.CODES/docs.").waitFor();
  await browser.evaluate(() => {
    const paragraph = document.querySelector("[data-user-message-body] p");
    if (!paragraph) throw new Error("No source paragraph");
    const range = document.createRange();
    range.selectNodeContents(paragraph);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    return null;
  });
  await browser.keyboard.press("ControlOrMeta+C");
  await screen.getByRole("textbox").tap();
  await browser.keyboard.press("ControlOrMeta+V");
  await app.screenshot("pasted-composer");
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete").waitFor();
  await app.screenshot("sent-link");
  const href = await browser.evaluate(() => {
    const messages = [...document.querySelectorAll("[data-user-message-body]")].filter(body => body.textContent?.includes("Explicit:"));
    return messages.at(-1)?.querySelector("a")?.getAttribute("href") ?? null;
  });
  expect(href).toBe("https://t3.codes/docs.");
});
