/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Explicit table sections remain siblings and copy every row", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("table-demo", Object.fromEntries(["tfoot", "tbody"].map(section => [`${section}.md`, `<table><tr><td>One</td></tr><${section}><tr><td>Total</td></tr></${section}></table>`])));
  await t3.open();
  await screen.getByTestId("composer-editor").waitFor();
  const results = [];
  for (const section of ["tfoot", "tbody"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(`${section}.md`);
    await screen.getByRole("option", `${section}.md`, { exact: false }).waitFor();
    await screen.getByPlaceholder("Search files…").press("Enter");
    await screen.getByRole("button", "Show rendered markdown").tap();
    await screen.getByRole("cell", "Total", { exact: true }).waitFor();
    await screen.getByRole("button", "Copy table", { exact: true }).tap();
    await screen.getByRole("menuitem", "Copy as Markdown", { exact: true }).tap();
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot(`${section}-render-and-copied-markdown`);
    results.push(await browser.evaluate(() => ({
      sections: [...document.querySelector(".chat-markdown-table-container table")!.children].map(e => e.tagName.toLowerCase()),
      pasted: document.querySelector('[role="textbox"]')?.textContent ?? "",
      nested: document.querySelectorAll(".chat-markdown-table-container table tbody tbody, .chat-markdown-table-container table tbody tfoot").length,
    })));
  }
  expect(results).toEqual([
    { sections: ["tbody", "tfoot"], pasted: expect.stringContaining("Total"), nested: 0 },
    { sections: ["tbody", "tbody"], pasted: expect.stringContaining("Total"), nested: 0 },
  ]);
});
