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

/** 用户偏好：含跟随系统 */
export type ThemePreference = 'light' | 'dark' | 'system';
/** 实际生效的明暗 */
export type ResolvedTheme = 'light' | 'dark';

interface AppState {
  themePreference: ThemePreference;
  setThemePreference: (mode: ThemePreference) => void;
  /** 三态循环：light → dark → system → light */
  cycleTheme: () => void;
}

export const useAppStore = create<AppState>()(
  persist(
    set => ({
      themePreference: 'system', // 默认跟随系统
      setThemePreference: themePreference => set({ themePreference }),
      cycleTheme: () =>
        set(s => {
          const order: ThemePreference[] = ['light', 'dark', 'system'];
          const i = order.indexOf(s.themePreference);
          return { themePreference: order[(i + 1) % order.length] };
        }),
    }),
    {
      name: 'app-store',
      partialize: s => ({ themePreference: s.themePreference }),
    },
  ),
);
