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

function image(color: string, width = 4000) {
  return execFileSync("convert", ["-size", `${width}x2400`, `xc:${color}`, "-fill", "white", "-draw", "rectangle 200,200 1800,1000", "-fill", "#16233b", "-draw", "rectangle 2100,1200 3800,2200", "png:-"]);
}

test("An unchanged workspace image preserves zoom, scroll and its expanded view across commands", WEB, async ({ t3, app, browser, screen }) => {
  const capture = async (label: string) => { await browser.mouse.move(300, 600); await app.screenshot(label); };
  const project = await t3.project("image-demo", { "big.png": image("#268aaf") });
  const thread = await t3.thread({ project, title: "Image preview", messages: ["run pwd, ls and git status"], model: "command-output" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="big.png"]');
      if (row) { row.click(); return true; }
    }
    return false;
  })).toBe(true);
  await screen.getByRole("button", "Zoom in", { exact: true }).tap();
  await screen.getByRole("button", "Zoom in", { exact: true }).tap();
  await screen.getByRole("button", "Zoom in", { exact: true }).tap();
  const original = await browser.evaluate(() => {
    const img = document.querySelector<HTMLImageElement>('img[alt="big.png"]')!;
    const scroller = img.closest('button')!.parentElement!.parentElement!;
    scroller.scrollLeft = 140;
    Object.assign(window, { originalImage: img });
    return { width: img.width, scroll: scroller.scrollLeft };
  });
  await capture("zoom-before-command");
  const cli = makeState(T3_HOME).cli;
  const send = async (message: string) => {
    await runPromise(cli(["thread", "send", thread.threadId, message, "--wait", "--json"]));
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  };
  await send("run pwd, ls and git status");
  await capture("zoom-after-command");
  const after = await browser.evaluate(() => {
    const img = document.querySelector<HTMLImageElement>('img[alt="big.png"]')!;
    return { same: img === (window as any).originalImage, width: img.width, scroll: img.closest('button')!.parentElement!.parentElement!.scrollLeft };
  });
  await screen.getByRole("button", "Zoom big.png", { exact: true }).tap();
  await capture("expanded-before-command");
  await send("run git status again");
  await capture("expanded-after-command");
  const expanded = await browser.evaluate(() => document.querySelectorAll('[role="dialog"]').length);
  await browser.keyboard.press("Escape");
  writeFileSync(`${project}/big.png`, image("#b95032", 4200));
  await send("show the rewritten image");
  await expect.poll(() => browser.evaluate(() => document.querySelector<HTMLImageElement>('img[alt="big.png"]')?.naturalWidth)).toBe(4200);
  await capture("rewritten-image");
  expect({ ...after, expanded }).toEqual({ same: true, width: original.width, scroll: original.scroll, expanded: 1 });
});
