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

const MESSAGE = "See https://t3.codes for details. Also https://de.wikipedia.org/wiki/Straße and https://T3.CODES/docs and https://t3.codes:443/docs and https://t3.codes?q=1 and https://t3.codes#top.";
const WEB_TEXT = "See https://t3.codes for details. Also https://de.wikipedia.org/wiki/Straße, https://T3.CODES/docs, https://t3.codes:443/docs, https://t3.codes?q=1 and https://t3.codes#top. Read the docs or https://t3.codes.";
const EXPECTED = "See https://t3.codes for details. Also https://de.wikipedia.org/wiki/Straße, https://T3.CODES/docs, https://t3.codes:443/docs, https://t3.codes?q=1 and https://t3.codes#top. Read [the docs](https://t3.codes/docs) or [https://t3.codes](https://example.org/other).";
const HTML = '<p>See <a href="https://t3.codes/">https://t3.codes</a> for details. Also <a href="https://de.wikipedia.org/wiki/Stra%C3%9Fe">https://de.wikipedia.org/wiki/Straße</a>, <a href="https://t3.codes/docs">https://T3.CODES/docs</a>, <a href="https://t3.codes/docs">https://t3.codes:443/docs</a>, <a href="https://t3.codes/?q=1">https://t3.codes?q=1</a> and <a href="https://t3.codes/#top">https://t3.codes#top</a>. Read <a href="https://t3.codes/docs">the docs</a> or <a href="https://example.org/other">https://t3.codes</a>.</p>';

test("Bare web URLs keep their displayed spelling through copy and paste", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("url-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 === "showcase"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({project, title: "Bare URL clipboard", messages: [MESSAGE], model: "showcase"});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent See/).tap();
  await browser.evaluate(() => {
    const paragraph = document.querySelector("[data-user-message-body] p");
    if (!paragraph) throw new Error("Rendered user message missing");
    const range = document.createRange();
    range.selectNodeContents(paragraph);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    return null;
  });
  await browser.keyboard.press("ControlOrMeta+C");
  const composer = screen.getByRole("textbox");
  await composer.tap();
  await browser.keyboard.press("ControlOrMeta+V");
  await app.screenshot("rendered-message-pasted");
  const copied = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent ?? "");
  await browser.keyboard.press("ControlOrMeta+A");
  await browser.keyboard.press("Backspace");
  // A static webpage fixture outside React supplies the browser's native rich clipboard.
  await browser.evaluate((html) => {
    const source = document.createElement("aside");
    source.id = "webpage-source";
    source.style.cssText = "position:fixed;inset:40px;background:white;color:black;padding:32px;z-index:99999";
    source.innerHTML = html;
    document.body.append(source);
    const range = document.createRange();
    range.selectNodeContents(source);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    return null;
  }, HTML);
  await browser.keyboard.press("ControlOrMeta+C");
  await browser.evaluate(() => { document.getElementById("webpage-source")?.remove(); return null; });
  await composer.tap();
  await browser.keyboard.press("ControlOrMeta+V");
  await app.screenshot("webpage-links-pasted");
  const pasted = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent ?? "");
  expect({copied, pasted}).toEqual({copied: MESSAGE, pasted: EXPECTED});
});
