import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { categoryMenuZIndex, ResourceSelectField } from "./ResourceSelectDrawer.jsx";

vi.mock("@/shared/ui/SideDrawer.jsx", () => ({
    SideDrawer({ children, drawerProps, onClose, open, title }) {
        if (!open) {
            return null;
        }
        return (
            <aside aria-label={title} data-z-index={drawerProps?.sx?.zIndex} role="dialog">
                <button type="button" onClick={onClose}>
                    关闭
                </button>
                {children}
            </aside>
        );
    },
}));

const resources = [
    {
        coinPrice: 10,
        name: "Rose Gift",
        priceType: "coin",
        resourceCode: "rose_gift",
        resourceId: 1,
        resourceType: "gift",
    },
    {
        coinPrice: 0,
        name: "VIP Vehicle",
        priceType: "free",
        resourceCode: "vip_vehicle",
        resourceId: 2,
        resourceType: "vehicle",
    },
];

test("resource select drawer stays above dialogs and filters by category", () => {
    render(<ResourceSelectField resources={resources} value="" />);

    fireEvent.click(screen.getByPlaceholderText("请选择资源"));

    expect(screen.getByRole("dialog", { name: "选择资源" })).toHaveAttribute("data-z-index", "1600");
    expect(screen.getByText("Rose Gift")).toBeInTheDocument();
    expect(screen.getByText("VIP Vehicle")).toBeInTheDocument();

    fireEvent.mouseDown(screen.getByRole("combobox", { name: "分类" }));
    expect(screen.getByTestId("resource-category-menu-root")).toHaveStyle(`z-index: ${categoryMenuZIndex}`);
    fireEvent.click(screen.getByRole("option", { name: "座驾" }));

    expect(screen.queryByText("Rose Gift")).not.toBeInTheDocument();
    expect(screen.getByText("VIP Vehicle")).toBeInTheDocument();
});

test("optional resource field can clear an existing binding without opening drawer", () => {
    const onChange = vi.fn();
    render(<ResourceSelectField onChange={onChange} required={false} resources={resources} value="2" />);

    fireEvent.click(screen.getByRole("button", { name: "清除资源" }));

    expect(onChange).toHaveBeenCalledWith("", null);
    expect(screen.queryByRole("dialog", { name: "选择资源" })).not.toBeInTheDocument();
});
