import { create } from 'zustand';
import AsyncStorage from '@react-native-async-storage/async-storage';

export type ThemeMode = 'light' | 'dark' | 'system';

interface ThemeState {
  mode: ThemeMode;
  setMode: (mode: ThemeMode) => Promise<void>;
  init: () => Promise<void>;
}

const STORAGE_KEY = '@theme_mode';

export const useThemeStore = create<ThemeState>((set) => ({
  mode: 'system',

  setMode: async (mode: ThemeMode) => {
    set({ mode });
    await AsyncStorage.setItem(STORAGE_KEY, mode);
  },

  init: async () => {
    try {
      const saved = await AsyncStorage.getItem(STORAGE_KEY);
      if (saved === 'light' || saved === 'dark' || saved === 'system') {
        set({ mode: saved });
      }
    } catch {}
  },
}));
