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

const TABLE = "| Name | Note |\n| --- | --- |\n| Acme™ | a |\n| ©2026 | b |\n| A↔B | c |\n| Plain | d |";

test("Copy for chat apps aligns text symbols", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("table-copy");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { providerInstances: {
      opencode: { driver: "opencode", enabled: true, config: {} },
    } } });
  }).pipe(Effect.scoped));
  const started = await runPromise(makeState(T3_HOME).cli([
    "thread", "start", project, "Reply with exactly this Markdown table and nothing else:\n" + TABLE,
    "--title", "Text symbols", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--wait", "--json",
  ]));
  const thread = JSON.parse(started.stdout);
  await browser.addInitScript(() => {
    const copied = Promise.withResolvers<string>();
    Object.assign(window, { copiedTable: copied.promise });
    navigator.clipboard.write = async ([item]) => {
      copied.resolve(await (await item.getType("text/plain")).text());
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "Copy table", { exact: true }).tap();
  await screen.getByRole("menuitem", "Copy for chat apps", { exact: true }).tap();
  const text = await browser.evaluate(async () => {
    const text = await (window as unknown as { copiedTable: Promise<string> }).copiedTable;
    const panel = document.createElement("section");
    panel.style.cssText = "position:fixed;right:24px;bottom:100px;z-index:9999;background:#fff;color:#111;padding:24px;border:2px solid #888;border-radius:8px;box-shadow:0 4px 24px #0004";
    const title = document.createElement("h2");
    title.textContent = "Copy for chat apps — clipboard text/plain";
    title.style.cssText = "font:16px sans-serif;margin:0 0 16px";
    const pre = document.createElement("pre");
    pre.style.cssText = "font:28px/1.6 'DejaVu Sans Mono',monospace;margin:0;white-space:pre";
    pre.textContent = text;
    panel.append(title, pre);
    document.body.append(panel);
    return text;
  });
  await app.screenshot("copied-table-alignment");
  const lines = text.replace(/^```[^\n]*\n|\n```$/g, "").split("\n");
  const positions = lines.filter(line => /^(Name|Acme|©|A↔B|Plain)/.test(line)).map(line => line.search(/(?:Note|[abcd])\s*$/));
  expect(positions).toEqual([positions[0], positions[0], positions[0], positions[0], positions[0]]);
});
