import { fireEvent, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../../test/utils";

vi.mock("../../hooks/useSubscription", () => ({
    useSubscription: () => ({ hasFeature: () => true }),
}));

import { useAuthStore } from "../../stores/authStore";
import Sidebar from "./Sidebar";

describe("Sidebar — expandable نوبت‌ها menu", () => {
    beforeEach(() => {
        useAuthStore.setState({
            primaryRole: "admin",
            dbUuid: "c1",
            userName: "ادمین",
            availableContexts: [],
            context: null,
        } as any);
    });

    it("keeps نوبت‌ها always expanded regardless of route and click", () => {
        renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });

        // منوی والد به شکل دکمه
        const parent = screen.getByRole("button", { name: /نوبت‌ها/ });
        expect(parent).toBeInTheDocument();

        // حتی خارج از مسیر نوبت‌ها، زیرمنوها همیشه دیده می‌شوند
        expect(screen.getByText("نوبت ها")).toBeInTheDocument();
        expect(screen.getByText("افزودن نوبت")).toBeInTheDocument();

        // کلیک روی والد آن را جمع نمی‌کند
        fireEvent.click(parent);
        expect(screen.getByText("نوبت ها")).toBeInTheDocument();
        expect(screen.getByText("افزودن نوبت")).toBeInTheDocument();
    });

    it("auto-expands when a child route is active", () => {
        renderWithProviders(<Sidebar />, { route: "/admin/appointments/new" });
        // چون «افزودن نوبت» فعال است، منو باید خودکار باز باشد
        expect(screen.getByText("افزودن نوبت")).toBeInTheDocument();
        expect(screen.getByText("نوبت ها")).toBeInTheDocument();
    });
});

describe("Sidebar — خدمات در منوی اصلی (نه تنظیمات)", () => {
    it("shows خدمات in the clinic main menu linking to /admin/clinic-services", () => {
        useAuthStore.setState({
            primaryRole: "clinic",
            dbUuid: "c1",
            userName: "کلینیک",
            availableContexts: [],
            context: null,
        } as any);
        renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });
        expect(screen.getByText("سرویس ها").closest("a")).toHaveAttribute(
            "href",
            "/admin/clinic-services",
        );
    });

    it("shows خدمات in the doctor main menu linking to /admin/clinic-services", () => {
        useAuthStore.setState({
            primaryRole: "doctor",
            dbUuid: null,
            userName: "پزشک",
            availableContexts: [],
            context: null,
        } as any);
        renderWithProviders(<Sidebar />, { route: "/admin/dashboard" });
        expect(screen.getByText("سرویس ها").closest("a")).toHaveAttribute(
            "href",
            "/admin/clinic-services",
        );
    });
});
