import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { IOS, test } from "./t3-mobile.ts";

test("An off-centre image pinch remains enlarged after release", IOS, async ({t3, app, screen, device}) => {
  const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="300"><rect width="600" height="300" fill="#00aa55"/><rect width="200" height="300" fill="#ee2222"/><text x="30" y="150" font-size="32" fill="white">LEFT</text><text x="350" y="150" font-size="32" fill="white">RIGHT</text></svg>';
  const project = await t3.project("Image proof", {"chart.svg": svg});
  await t3.thread({project, title:"Image proof", messages:["![Zoom chart](chart.svg)"]});
  await t3.open();
  await screen.getByText("Image proof", {exact:true}).last().tap();
  await screen.getByRole("button", {name: /Agent:/}).tap();
  const image = device.locator('label="Zoom chart"').first();
  await image.waitFor({state:"visible", timeout:120000});
  const frame = await image.boundingBox();
  if (!frame) throw new Error("Image has no frame");
  await app.screenshot("fit");
  await device.unstable_raw.client.interactions.pinch({scale:3,x:frame.x+frame.width*0.17,y:frame.y+frame.height*0.55});
  const capture = await app.screenshot("released-off-centre-zoom");
  const size = execFileSync("identify", ["-format","%w",capture], {encoding:"utf8"});
  const screenWidth = 402;
  const ratio = Number(size)/screenWidth;
  const x = Math.round((frame.x+frame.width*0.5)*ratio);
  const y = Math.round((frame.y+frame.height*0.7)*ratio);
  const pixel = execFileSync("convert", [capture,"-format",`%[pixel:p{${x},${y}}]`,"info:"], {encoding:"utf8"});
  expect(pixel).toMatch(/238,\s*34,\s*34/);
});
