import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A file submenu flips left at the right edge and opens right when there is room", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("submenu-demo", { "README.md": "# Submenu example\n" });
  const thread = await t3.thread({ project, title: "Menu positioning", messages: ["Ready"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", /^Files/).tap();
  const row = screen.getByRole("treeitem", "README.md", { exact: true });
  const bounds = await row.boundingBox();
  const pointer = (screen as unknown as { context: { engine: { performAt(point: {x:number;y:number}, action: {kind: "secondaryTap"}, timeout?: number): Promise<void> } } }).context.engine;
  const y = bounds!.y + bounds!.height / 2;
  const geometry = () => browser.evaluate(() => Array.from(document.querySelectorAll('[data-context-menu="true"]')).map(el => { const r = el.getBoundingClientRect(); return { x: r.x, right: r.right, width: r.width }; }));
  await pointer.performAt({ x: 1100, y }, { kind: "secondaryTap" });
  await screen.getByRole("menuitem", "Open with").hover();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
  await app.screenshot("right-edge-submenu");
  const edge = await geometry();
  await browser.keyboard.press("Escape");
  await pointer.performAt({ x: 800, y }, { kind: "secondaryTap" });
  await screen.getByRole("menuitem", "Open with").hover();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
  await app.screenshot("room-on-right-control");
  const control = await geometry();
  console.log(JSON.stringify({ y, edge, control }));
  expect(control[1].x).toBeGreaterThanOrEqual(control[0].right - 2);
  expect(edge[1].right).toBeLessThanOrEqual(edge[0].x + 2);
});
