import { describe, expect, it, vi } from "vitest";
import type { Page } from "playwright";

function mockOverlayPage(overlays: Array<{ visible: boolean; hasCargo: boolean }>): Page {
  const overlayLocs = overlays.map((o) => ({
    isVisible: vi.fn(async () => o.visible),
    locator: vi.fn(() => ({
      first: vi.fn(() => ({
        isVisible: vi.fn(async () => o.hasCargo),
      })),
    })),
  }));
  return {
    locator: vi.fn(() => ({
      count: vi.fn(async () => overlayLocs.length),
      nth: vi.fn((i: number) => overlayLocs[i]),
    })),
    keyboard: { press: vi.fn(async () => undefined) },
    waitForTimeout: vi.fn(async () => undefined),
  } as unknown as Page;
}

describe("isCargoOverlayPopoverOpen", () => {
  it("无 dialog 货物弹层时返回 false", async () => {
    const { isCargoOverlayPopoverOpen } = await import("@/workers/rpa/cargo-lock");
    const page = mockOverlayPage([]);
    expect(await isCargoOverlayPopoverOpen(page)).toBe(false);
  });

  it("dialog 含 pallet 输入时返回 true", async () => {
    const { isCargoOverlayPopoverOpen } = await import("@/workers/rpa/cargo-lock");
    const page = mockOverlayPage([{ visible: true, hasCargo: true }]);
    expect(await isCargoOverlayPopoverOpen(page)).toBe(true);
  });
});

describe("dismissCargoPopoverOnly", () => {
  it("内联货物（无 overlay）不按 Escape", async () => {
    const { dismissCargoPopoverOnly } = await import("@/workers/rpa/cargo-lock");
    const page = mockOverlayPage([]);
    await dismissCargoPopoverOnly(page, "#widget");
    expect(page.keyboard.press).not.toHaveBeenCalled();
  });
});
