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

export type AppLanguage = 'de' | 'en';

const STORAGE_KEY = '@rebreak/language';

type LanguageState = {
  language: AppLanguage;
  setLanguage: (lang: AppLanguage) => Promise<void>;
  init: () => Promise<void>;
};

export const useLanguageStore = create<LanguageState>((set) => ({
  language: 'en',

  init: async () => {
    const stored = await AsyncStorage.getItem(STORAGE_KEY);
    if (stored === 'de' || stored === 'en') {
      await i18n.changeLanguage(stored);
      set({ language: stored });
    } else {
      // Kein expliziter Wert gespeichert — i18n.ts hat bereits via deviceLocale
      // initialisiert (Localization.getLocales()). NICHT auf 'en' overriden.
      set({ language: (i18n.language === 'de' ? 'de' : 'en') as AppLanguage });
    }
  },

  setLanguage: async (lang) => {
    await AsyncStorage.setItem(STORAGE_KEY, lang);
    await i18n.changeLanguage(lang);
    set({ language: lang });
  },
}));
