import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Copy a chat table as HTML for rich and plain paste", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const markdown = "## Quarterly results\n\n| Product (left) | Status (center) | Revenue (right) |\n| :--- | :---: | ---: |\n| Alpha | Ready | $1,200 |\n| Beta | Review | $840 |\n| Gamma | Ready | $2,050 |";
  const lines = original.trim().split("\n").map(line => {
    const entry = JSON.parse(line);
    if (entry.frame?.params?.update?.sessionUpdate === "agent_message_chunk") entry.frame.params.update.content.text = markdown;
    return JSON.stringify(entry);
  });
  await writeFile(fixture, lines.join("\n") + "\n");
  let thread;
  try {
    const project = await t3.project("Table export demo");
    thread = await t3.thread({ project, title: "Copy a quarterly table", model: "showcase", messages: ["Show a table with left, center and right aligned columns."] });
  } finally { await writeFile(fixture, original); }
  await t3.open(thread!);
  await screen.getByRole("button", "Copy table").tap();
  await app.screenshot("table-copy-menu");
  await expect(screen.getByRole("menuitem", "Copy as HTML")).toBeVisible();
  await screen.getByRole("menuitem", "Copy as HTML").tap();
  await screen.getByRole("button", "Copied").waitFor({ state: "visible" });
  await browser.evaluate(() => {
    const panel = document.createElement("section");
    panel.id = "paste-demo";
    panel.style.cssText = "position:fixed;inset:80px 40px 40px 300px;z-index:9999;background:white;color:#111;padding:28px;overflow:auto;font:16px system-ui;border:2px solid #555";
    panel.innerHTML = '<h1>HTML clipboard paste demonstration</h1><p>Rich-text editor — paste with Ctrl+V</p><div contenteditable="true" role="textbox" aria-label="Rich text paste target" style="min-height:140px;border:1px solid #aaa;padding:12px"></div><p>Plain-text editor — paste with Ctrl+V</p><textarea aria-label="Plain text paste target" style="width:100%;height:220px;font:12px monospace"></textarea>';
    document.body.append(panel);
  });
  await screen.getByRole("textbox", "Rich text paste target").tap();
  await browser.keyboard.press("Control+V");
  await screen.getByRole("textbox", "Plain text paste target").tap();
  await browser.keyboard.press("Control+V");
  await browser.evaluate(() => {
    const plain = document.querySelector('[aria-label="Plain text paste target"]') as HTMLTextAreaElement;
    plain.style.height = "390px";
    plain.scrollTop = 0;
  });
  await app.screenshot("html-pasted-rich-and-plain");
  const pasted = await browser.evaluate(() => {
    const rich = document.querySelector('[aria-label="Rich text paste target"]')!;
    return {
      html: rich.innerHTML,
      plain: (document.querySelector('[aria-label="Plain text paste target"]') as HTMLTextAreaElement).value,
      align: [...rich.querySelectorAll("th")].map(c => (c as HTMLElement).style.textAlign),
      border: [...rich.querySelectorAll("th,td")].every(c => getComputedStyle(c).borderTopStyle === "solid"),
      shaded: [...rich.querySelectorAll("th")].every(c => getComputedStyle(c).backgroundColor === "rgb(246, 248, 250)")
    };
  });
  expect(pasted.html).toContain("<table");
  expect(pasted.plain).toContain("<table");
  expect(pasted.plain).toContain("<th");
  expect(pasted.align).toEqual(["left", "center", "right"]);
  expect(pasted.border).toBe(true);
  expect(pasted.shaded).toBe(true);
});
