import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface DashboardState {
  viewAsUser: boolean;
}

// Load initial state from localStorage if available
const getInitialViewAsUser = (): boolean => {
  try {
    const stored = localStorage.getItem('dashboard_viewAsUser');
    return stored ? JSON.parse(stored) : false;
  } catch {
    return false;
  }
};

const initialState: DashboardState = {
  viewAsUser: getInitialViewAsUser(),
};

const dashboardSlice = createSlice({
  name: 'dashboard',
  initialState,
  reducers: {
    setViewAsUser: (state, action: PayloadAction<boolean>) => {
      state.viewAsUser = action.payload;
      // Persist to localStorage
      localStorage.setItem('dashboard_viewAsUser', JSON.stringify(action.payload));
    },
  },
});

export const { setViewAsUser } = dashboardSlice.actions;
export default dashboardSlice;

