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

const CONTENT = "region,revenue\nNorth,1200\nSouth,950\n";

test("Save a nested workspace CSV from chat and the file panel", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1440, height: 900 });
  const project = await t3.project("sales-demo", { "reports/sales-q3.csv": CONTENT });
  const thread = await t3.thread({ project, title: "Quarterly sales", messages: ['See [sales-q3.csv](reports/sales-q3.csv) and [bare sales file](sales-q3.csv)'] });
  await t3.open(thread);
  // Workspace tooltips contain the runner's private absolute paths.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[data-slot="tooltip-positioner"] { visibility: hidden !important; }';
    document.head.append(style);
  });
  await screen.getByRole("button", /^Agent See/).tap();
  const links = screen.getByRole("link", /^sales-q3\.csv/);
  const download = async (trigger: () => Promise<void>) => {
    const saved = await browser.waitForDownload(trigger);
    expect(saved.suggestedFilename).toBe("sales-q3.csv");
    expect(await readFile(saved.absolutePath, "utf8")).toBe(CONTENT);
  };
  await links.first().press("Shift+F10");
  await app.screenshot("chat-file-menu");
  await download(() => screen.getByRole("menuitem", "Download", { exact: true }).press("Enter"));
  await links.nth(1).press("Shift+F10");
  await download(() => screen.getByRole("menuitem", "Download", { exact: true }).press("Enter"));
  await app.screenshot("bare-filename-saved");
  await links.first().press("Enter");
  await screen.getByText("North", { exact: true }).waitFor();
  await browser.mouse.move(600, 500);
  await app.screenshot("csv-file-panel");
  const save = screen.getByRole("button", "Save file", { exact: true });
  await expect(save).toHaveCount(1);
  await download(() => save.tap());
  await browser.mouse.move(600, 500);
  await app.screenshot("csv-saved");
});
