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

export type Language = "en" | "am" | "fr" | "ti" | "om";

interface LangState {
  language: Language;
  setLanguage: (language: Language) => void;
}

const LANGUAGE_STORAGE_KEY = "app_language";

export const useLangStore = create<LangState>((set) => {
  // Hydrate language from AsyncStorage (non-blocking)
  (async () => {
    try {
      const stored = await AsyncStorage.getItem(LANGUAGE_STORAGE_KEY);
      if (
        stored === "en" ||
        stored === "am" ||
        stored === "fr" ||
        stored === "ti" ||
        stored === "om"
      ) {
        set({ language: stored as Language });
      }
    } catch (error) {
      if (__DEV__) {
        console.warn("Failed to load language from storage", error);
      }
    }
  })();

  return {
    language: "en",
    setLanguage: (language: Language) => {
      set({ language });
      AsyncStorage.setItem(LANGUAGE_STORAGE_KEY, language).catch((error) => {
        if (__DEV__) {
          console.warn("Failed to persist language", error);
        }
      });
    },
  };
});
