import { useEffect, useMemo } from "react";
import { useSelector } from "react-redux";
import { selectCurrentUser } from "~/store/features/auth/authSlice";
import useLocalStorage from "../useLocalStorage";

export const useAuth = () => {
  const user = useSelector(selectCurrentUser);
  const [storedUser, setStoredUser] = useLocalStorage("authUser", {
    access: "",
    refresh: "",
    user: { pk: 0, username: "", email: "", first_name: "", last_name: "" },
  });

  useEffect(() => {
    if (user) {
      setStoredUser(user);
    }
  }, [user, setStoredUser]);

  // Use memo to return the stored user or the current user
  return useMemo(() => {
    return { user: storedUser || user };
  }, [storedUser, user]);
};
