import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

interface CustomizerState {
  activeMode: 'light' | 'dark';
  isCollapse: boolean;
  isMobileSidebar: boolean;
  sidebarWidth: number;
  miniSidebarWidth: number;
  isHydrated: boolean;

  setDarkMode: (mode: 'light' | 'dark') => void;
  toggleSidebar: () => void;
  toggleMobileSidebar: () => void;
  setHydrated: () => void;
}

export const useCustomizerStore = create<CustomizerState>()(
  persist(
    (set) => ({
      activeMode: 'light',
      isCollapse: false,
      isMobileSidebar: false,
      sidebarWidth: 270,
      miniSidebarWidth: 87,
      isHydrated: false,

      setDarkMode: (mode) => set({ activeMode: mode }),

      toggleSidebar: () =>
        set((state) => ({
          isCollapse: !state.isCollapse,
        })),

      toggleMobileSidebar: () =>
        set((state) => ({
          isMobileSidebar: !state.isMobileSidebar,
        })),

      setHydrated: () => set({ isHydrated: true }),
    }),
    {
      name: 'modernize-layout-settings',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        activeMode: state.activeMode,
        isCollapse: state.isCollapse,
      }),
      onRehydrateStorage: () => (state) => {
        state?.setHydrated();
      },
    }
  )
);
