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

export type ThemeModeType = 'auto' | 'light' | 'dark';
export interface RootLayoutState {
    themeMode: ThemeModeType;
    themeCompact: boolean;
}

export const getStorageTheme = () => {
    const tm = ThemeMode.get();
    if (tm) {
        return tm;
    }
    return { themeMode: 'light', themeCompact: document.body.clientWidth < 1920 } as RootLayoutState;
};

const initialState: RootLayoutState = getStorageTheme();

export const counterSlice = createSlice({
    name: 'rootLayout',
    initialState,
    reducers: {
        setThemeMode: (state, action: PayloadAction<ThemeModeType>) => {
            state.themeMode = action.payload;
        },
        setThemeCompact: (state, action: PayloadAction<boolean>) => {
            state.themeCompact = action.payload;
        },
    },
});

export const { setThemeMode, setThemeCompact } = counterSlice.actions;
export default counterSlice.reducer;
