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

test("Select all confines selection to the rendered preview including CSV headers", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1920, height: 1080 });
  const project = await t3.project("csvproj", {
    "cities.csv": "City,Country,Population\nLondon,UK,8982000\nParis,France,2161000\nTokyo,Japan,13960000\nBerlin,Germany,3645000\n",
    "large.log": Array.from({ length: 6000 }, (_, i) => `Entry ${i + 1}: Preview diagnostic content\n`).join("") + `${"Additional diagnostic context ".repeat(40)}\n`.repeat(60000),
  });
  const thread = await t3.thread({ project, title: "Review cities", messages: ["CHAT_SENTINEL: review the city table"], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Review cities").waitFor();
  const results: Array<{ file: string; selected: string }> = [];
  for (const file of ["cities.csv", "large.log"]) {
    await browser.keyboard.press("ControlOrMeta+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, { exact: false }).tap();
    const cell = file === "cities.csv" ? screen.getByText("London", { exact: true }) : browser.locator('[data-preview-row="0"]');
    await cell.waitFor({ timeout: 120000 });
    if (file === "cities.csv") await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
    await cell.tap();
    await browser.keyboard.press("ControlOrMeta+a");
    const selected = await browser.evaluate(() => window.getSelection()?.toString() ?? "");
    results.push({ file, selected });
    await app.screenshot(file === "cities.csv" ? "table-select-all" : "large-text-select-all");
    // Keep the selection visible in the recording for human inspection.
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2000)));
    await browser.evaluate(() => { window.getSelection()?.removeAllRanges(); return null; });
  }
  for (const result of results) {
    expect(result.selected).not.toContain("CHAT_SENTINEL");
    if (result.file === "cities.csv") {
      expect(result.selected).toContain("City");
      expect(result.selected).toContain("Country");
      expect(result.selected).toContain("London");
      expect(result.selected).toContain("Berlin");
    } else expect(result.selected).toContain("Entry 1:");
  }
});
