import { User as FirebaseUser } from "firebase/auth"; 
import { createContext, ReactNode, useContext, useMemo, useState } from "react";

type UserContextType = {
  user: FirebaseUser | null;
  role: string | null;
  setUser: (user: FirebaseUser | null) => void;
  setRole: (role: string | null) => void;
};

const UserContext = createContext<UserContextType | null>(null);

type UserProviderProps = {
  children: ReactNode;
};

export const UserProvider = ({ children }: UserProviderProps) => {
  const [user, setUser] = useState<FirebaseUser | null>(null);
  const [role, setRole] = useState<string | null>(null);

  const value = useMemo(
    () => ({ user, role, setUser, setRole }),
    [user, role]
  );

  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
};

export const useUser = () => {
  const context = useContext(UserContext);

  if (!context) {
    throw new Error("useUser doit être utilisé dans <UserProvider>");
  }
  return context;
};
