import { createSlice } from "@reduxjs/toolkit";

const getInitialState = () => {
  if (typeof window === "undefined") {
    return { user: null, isLoaded: false };
  }
  const user = JSON.parse(localStorage.getItem("user") || "null");
  return {
    user: user,
    isLoaded: !!user,
  };
};

const profileSlice = createSlice({
  name: "profile",
  initialState: getInitialState(),
  reducers: {
    setProfile(state, action) {
      state.user = action.payload;
      state.isLoaded = true;
      if (typeof window !== "undefined") {
        localStorage.setItem("user", JSON.stringify(action.payload));
      }
    },
    clearProfile(state) {
      state.user = null;
      state.isLoaded = false;
      if (typeof window !== "undefined") {
        localStorage.removeItem("user");
      }
    },
  },
});

export const { setProfile, clearProfile } = profileSlice.actions;
export default profileSlice.reducer;