import { create } from 'zustand';
import { Platform } from 'react-native';
import * as SecureStore from 'expo-secure-store';

const TOKEN_KEY = 'auth_token';

// expo-secure-store crashe sur web (son shim ~13.0.0 n'implémente pas
// getValueWithKeyAsync) — pas de vrai stockage sécurisé disponible dans un
// navigateur de toute façon, donc localStorage en fallback web uniquement.
// Le natif (iOS/Android) continue d'utiliser SecureStore normalement.
const tokenStorage = Platform.OS === 'web'
  ? {
      getItemAsync: async (key: string) => localStorage.getItem(key),
      setItemAsync: async (key: string, value: string) => localStorage.setItem(key, value),
      deleteItemAsync: async (key: string) => localStorage.removeItem(key),
    }
  : SecureStore;

type AuthState = {
  token: string | null;
  isLoading: boolean;
  setToken: (token: string | null) => Promise<void>;
  restoreToken: () => Promise<void>;
};

export const useAuthStore = create<AuthState>((set) => ({
  token: null,
  isLoading: true,
  setToken: async (token) => {
    if (token) {
      await tokenStorage.setItemAsync(TOKEN_KEY, token);
    } else {
      await tokenStorage.deleteItemAsync(TOKEN_KEY);
    }
    set({ token });
  },
  restoreToken: async () => {
    const token = await tokenStorage.getItemAsync(TOKEN_KEY);
    set({ token, isLoading: false });
  },
}));
