import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import { jest } from "@jest/globals";

// --------------------
// Mock menuItems + permissionTypes using ES modules
// --------------------

jest.unstable_mockModule("../constants/menuItems.js", () => ({
  menuItems: [
    {
      Menu_Name: "Dashboard",
      SubFeatureName: "Dashboard",
      Path: "/dashboard",
      ShowInMenu: true,
    },
    {
      Menu_Name: "Users",
      SubFeatureName: "UserList",
      Path: "/users",
      ShowInMenu: true,
    },
  ],
}));

jest.unstable_mockModule("../constants/userConstants.js", () => ({
  permissionTypes: [
    { key: 1 }, // full
    { key: 2 }, // read
    { key: 3 }, // none
  ],
}));

// Import after mocks
const { UserProvider, useUser } = await import("../context/UserContext.js");

// --------------------
// Test Helper Component
// --------------------

function TestComponent() {
  const {
    user,
    permissions,
    login,
    logout,
    setUserPermissions,
  } = useUser();

  return (
    <div>
      <div data-testid="user">
        {user ? user.name : "no-user"}
      </div>

      <div data-testid="permissions-count">
        {permissions ? permissions.length : 0}
      </div>

      <button
        data-testid="login-btn"
        onClick={() => login({ name: "John" })}
      >
        Login
      </button>

      <button data-testid="logout-btn" onClick={logout}>
        Logout
      </button>

      <button
        data-testid="set-permissions-btn"
        onClick={() =>
          setUserPermissions([
            {
              SubFeatureName: "Dashboard",
              Permission_Id: 1,
            },
          ])
        }
      >
        Set Permissions
      </button>
    </div>
  );
}

// --------------------
// Tests
// --------------------

describe("UserProvider", () => {
  beforeEach(() => {
    localStorage.clear();
    jest.clearAllMocks();
  });

  it("loads user from localStorage on mount", async () => {
    localStorage.setItem("user", JSON.stringify({ name: "SavedUser" }));

    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );

    await waitFor(() => {
      expect(screen.getByTestId("user")).toHaveTextContent("SavedUser");
    });
  });

  it("login updates user and localStorage", async () => {
    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );

    screen.getByTestId("login-btn").click();

    await waitFor(() => {
      expect(screen.getByTestId("user")).toHaveTextContent("John");
    });

    expect(JSON.parse(localStorage.getItem("user")).name).toBe("John");
  });

  it("logout clears user and localStorage", async () => {
    localStorage.setItem("user", JSON.stringify({ name: "Test" }));

    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );

    screen.getByTestId("logout-btn").click();

    await waitFor(() => {
      expect(screen.getByTestId("user")).toHaveTextContent("no-user");
    });

    expect(localStorage.getItem("user")).toBeNull();
  });

  it("sets permissions correctly", async () => {
    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );

    screen.getByTestId("set-permissions-btn").click();

    await waitFor(() => {
      expect(screen.getByTestId("permissions-count")).not.toHaveTextContent("0");
    });

    const storedPermissions = JSON.parse(localStorage.getItem("permissions"));
    expect(storedPermissions.length).toBeGreaterThan(0);
  });

  it.skip("handles empty permissions gracefully", async () => {
    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );

    
  });

  it.skip("sets empty permissions if no matching menu items", async () => {
    render(
      <UserProvider>
        <TestComponent />
      </UserProvider>
    );


  });
});