/// <reference lib="dom" />
import * as FS from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise } from "./t3.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const TABLE = '<table><thead><tr><th>Item</th><th>Cost</th></tr></thead><tfoot><tr><td>Total</td><td>3</td></tr></tfoot><tbody><tr><td>a</td><td>1</td></tr><tr><td>b</td><td>2</td></tr></tbody></table>';

test("Table CSV, Markdown and selected text keep footer after body", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("table-copy");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await FS.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: { binaryPath: "opencode" } };
  await FS.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  const launched = await runPromise(cli(["thread", "start", project, "Do not use any tools. Reply with exactly this raw HTML table and nothing else, without a code fence: " + TABLE, "--title", "Footer table", "--provider", "opencode", "--model", "anthropic/claude-haiku-5-5", "--wait", "--json"]));
  const thread = JSON.parse(launched.stdout);
  await t3.open(thread);
  await screen.getByRole("cell", "Total", { exact: true }).waitFor();

  // Observe app clipboard writes, and show them beside the real rendered table.
  await browser.evaluate(() => {
    const panel = document.createElement("pre");
    panel.id = "clipboard-observer";
    panel.style.cssText = "position:fixed;right:16px;bottom:16px;width:490px;max-height:670px;overflow:auto;z-index:9999;background:#111827;color:#f9fafb;border:2px solid #94a3b8;border-radius:8px;padding:16px;font:12px/1.3 monospace;white-space:pre-wrap;pointer-events:none";
    panel.textContent = "Clipboard observer (actual app writes)";
    document.body.append(panel);
    const table = document.querySelector(".chat-markdown-table-container table");
    const entries: Record<string, string> = { "Table DOM section order": [...(table?.children ?? [])].map(node => node.tagName).join(" → ") };
    Object.assign(window, { copyEvidence: entries, copyLabel: "" });
    const record = (label: string, text: string) => {
      entries[label] = text;
      panel.textContent = "Clipboard observer (actual app writes)\n\n" + Object.entries(entries).map(([key, value]) => key + "\n" + value).join("\n\n");
    };
    Object.defineProperty(navigator.clipboard, "writeText", { configurable: true, value: async (text: string) => {
      record((window as any).copyLabel, text);
    }});
    Object.defineProperty(navigator.clipboard, "write", { configurable: true, value: async (items: ClipboardItem[]) => {
      for (const item of items) for (const type of item.types) {
        const text = await (await item.getType(type)).text();
        record((window as any).copyLabel + (type === "text/html" ? " (HTML flavor)" : ""), text);
      }
    }});
    window.addEventListener("copy", event => {
        if ((window as any).copyLabel !== "Selected table — text/plain") return;
        record("Selected table — text/plain", event.clipboardData?.getData("text/plain") ?? "");
        record("Selected HTML includes footer", String(event.clipboardData?.getData("text/html").includes("<tfoot>")));
    });
    return null;
  });

  for (const format of ["CSV", "Markdown", "HTML"]) {
    await browser.evaluate(label => { (window as any).copyLabel = label; return null; }, "Copy as " + format);
    await screen.getByRole("button", /^(Copy table|Copied)$/).tap();
    await screen.getByRole("menuitem", "Copy as " + format, { exact: true }).tap();
    await screen.getByText("Copy as " + format, { exact: false }).waitFor();
  }
  // HTML has been observed; keep the compact text formats readable in the capture.
  await browser.evaluate(() => {
    const data = (window as any).copyEvidence;
    const html = data["Copy as HTML"];
    delete data["Copy as HTML"];
    delete data["Copy as HTML (HTML flavor)"];
    data["Copy as HTML includes footer"] = String(html.includes("<tfoot>"));
    const table = document.querySelector(".chat-markdown-table-container table");
    if (!table) throw new Error("Rendered table missing");
    (window as any).copyLabel = "Selected table — text/plain";
    const range = document.createRange();
    range.selectNode(table);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    return null;
  });
  await browser.keyboard.press("ControlOrMeta+C");
  await screen.getByText("Selected HTML includes footer", { exact: false }).waitFor();
  await app.screenshot("table-and-clipboard");
  const actual = await browser.evaluate(() => (window as any).copyEvidence);
  expect(actual["Copy as CSV"]).toBe("Item,Cost\na,1\nb,2\nTotal,3");
  expect(actual["Copy as Markdown"]).toBe("| Item | Cost |\n| --- | --- |\n| a | 1 |\n| b | 2 |\n| Total | 3 |");
  expect(actual["Selected table — text/plain"]).toBe(actual["Copy as Markdown"]);
});
