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

interface ThemeState {
  isDark: boolean;
  toggleTheme: () => void;
  setTheme: (isDark: boolean) => void;
}

export const useTheme = create<ThemeState>()(
  persist(
    (set) => ({
      isDark: typeof window !== 'undefined' ? window.matchMedia('(prefers-color-scheme: dark)').matches : false,
      toggleTheme: () => {
        set((state) => {
          const newIsDark = !state.isDark;
          if (typeof window !== 'undefined') {
            document.documentElement.classList.toggle('dark', newIsDark);
          }
          return { isDark: newIsDark };
        });
      },
      setTheme: (isDark: boolean) => {
        set({ isDark });
        if (typeof window !== 'undefined') {
          document.documentElement.classList.toggle('dark', isDark);
        }
      },
    }),
    {
      name: 'edr-theme',
      onRehydrateStorage: () => (state) => {
        if (state && typeof window !== 'undefined') {
          document.documentElement.classList.toggle('dark', state.isDark);
        }
      },
    }
  )
);
