import { describe, expect, it, vi } from "vitest";
import type { Page } from "playwright";
import { isCargoEditorOpen } from "@/workers/rpa/cargo-editor";

function mockPage(visible: (selector: string) => boolean): Page {
  const getByRole = vi.fn((_role: string, opts?: { name?: RegExp }) => ({
    first: () => ({
      isVisible: vi.fn().mockResolvedValue(
        opts?.name?.test("ADD ITEM") ?? false,
      ),
    }),
  }));
  const getByPlaceholder = vi.fn((pattern: RegExp) => ({
    first: () => ({
      isVisible: vi.fn().mockResolvedValue(/weight/i.test(pattern.source)),
    }),
  }));
  return {
    locator: vi.fn((selector: string) => ({
      first: () => ({
        isVisible: vi.fn().mockResolvedValue(visible(selector)),
      }),
      last: () => ({
        isVisible: vi.fn().mockResolvedValue(visible(selector)),
      }),
    })),
    getByRole,
    getByPlaceholder,
    getByText: vi.fn(() => ({
      first: () => ({ isVisible: vi.fn().mockResolvedValue(false) }),
    })),
  } as unknown as Page;
}

describe("isCargoEditorOpen", () => {
  it("role=dialog 可见时视为已打开", async () => {
    const page = mockPage((s) => s.includes("dialog"));
    expect(await isCargoEditorOpen(page)).toBe(true);
  });

  it("popover：Weight placeholder 可见时视为已打开（无 dialog）", async () => {
    const page = mockPage(() => false);
    expect(await isCargoEditorOpen(page)).toBe(true);
  });

  it("无 dialog 且无 editor 信号时未打开", async () => {
    const page = {
      locator: vi.fn(() => ({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(false),
        }),
      })),
      getByRole: vi.fn(() => ({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(false),
        }),
      })),
      getByPlaceholder: vi.fn(() => ({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(false),
        }),
      })),
      getByText: vi.fn(() => ({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(false),
        }),
      })),
    } as unknown as Page;

    expect(await isCargoEditorOpen(page)).toBe(false);
  });
});
