// import { configureStore } from '@reduxjs/toolkit';
// import loginReducer from './auth/store/loginSlice';
// import userReducer from './auth/store/userSlice';
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import type { TypedUseSelectorHook } from 'react-redux';
import { useSelector, useDispatch } from 'react-redux';

import loginReducer from './auth/store/loginSlice';
import userReducer from './auth/store/userSlice';

// export const store = configureStore({
//   reducer: {
//     login: loginReducer,
//     user: userReducer,
//   },
// });

// // tipe untuk dispatch
// export type AppDispatch = typeof store.dispatch;
// export type RootState = ReturnType<typeof store.getState>;

// 1. Buat root reducer
const rootReducer = combineReducers({
  login: loginReducer,
  user: userReducer,
});

// 2. Konfigurasi persist hanya untuk user
const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['user'], // hanya user yang di-persist
};

// 3. Wrap reducer dengan persistReducer
const persistedReducer = persistReducer(persistConfig, rootReducer);

// 4. Buat store
export const store = configureStore({
  reducer: persistedReducer,
  devTools: true,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [
          'persist/PERSIST',
          'persist/REHYDRATE',
          'persist/PAUSE',
          'persist/FLUSH',
          'persist/PURGE',
          'persist/REGISTER',
        ],
      },
    }),
});

// 5. Buat persistor
export const persistor = persistStore(store);

// 6. TypeScript types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// 7. Typed hooks
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
