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

type Theme = 'light' | 'dark' | 'system';

interface ThemeState {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  resolvedTheme: 'light' | 'dark';
}

const getSystemTheme = (): 'light' | 'dark' => 
  window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      theme: 'system',
      resolvedTheme: getSystemTheme(),
      
      setTheme: (theme: Theme) => {
        const resolved = theme === 'system' ? getSystemTheme() : theme;
        set({ theme, resolvedTheme: resolved });
        applyTheme(resolved);
      },

      toggleTheme: () => {
        const { theme, resolvedTheme } = get();
        // Toggle explicitly between light and dark when user manually overrides
        const nextTheme: Theme = resolvedTheme === 'dark' ? 'light' : 'dark';
        
        set({ theme: nextTheme, resolvedTheme: nextTheme });
        applyTheme(nextTheme);
      },
    }),
    {
      name: 'nextgen-theme-storage',
      onRehydrateStorage: () => (state) => {
        if (state) {
          const resolved = state.theme === 'system' ? getSystemTheme() : state.theme;
          state.resolvedTheme = resolved as 'light' | 'dark';
          applyTheme(resolved as 'light' | 'dark');
        }
      },
    }
  )
);

function applyTheme(theme: 'light' | 'dark') {
  const root = window.document.documentElement;
  root.classList.remove('light', 'dark');
  root.classList.add(theme);
}

// Initialize system listener
if (typeof window !== 'undefined') {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        const { theme } = useThemeStore.getState();
        if (theme === 'system') {
            const nextResolved = e.matches ? 'dark' : 'light';
            useThemeStore.setState({ resolvedTheme: nextResolved });
            applyTheme(nextResolved);
        }
    });
}
