import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import en from '@/src/i18n/locales/en.json';
import pl from '@/src/i18n/locales/pl.json';

const LANG_KEY = 'dailymeals.lang';

export async function initI18n() {
  const stored = await AsyncStorage.getItem(LANG_KEY);
  const lng = stored === 'pl' ? 'pl' : 'en';

  await i18n.use(initReactI18next).init({
    resources: { en: { translation: en }, pl: { translation: pl } },
    lng,
    fallbackLng: 'en',
    interpolation: { escapeValue: false },
  });
}

export async function setAppLanguage(code: 'en' | 'pl') {
  await AsyncStorage.setItem(LANG_KEY, code);
  await i18n.changeLanguage(code);
}

export default i18n;
