hatalar:
 ERROR  i18next::pluralResolver: Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.


i18next kodları da bunlar:
// src/i18n/index.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './en.json';
import tr from './tr.json';
import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
import 'moment/locale/tr';
import * as Localization from 'expo-localization';
import { LANGUAGE_PREFERENCE } from './constants';

const resources = {
  en: {
    translation: en
  },
  tr: {
    translation: tr
  }
};

const getDeviceLanguage = () => {
  const lang = Localization.locale.split('-')[0];
  if (lang === 'tr') return 'tr';
  return 'en';
};

const initI18n = async () => {
  let language = getDeviceLanguage();

  try {
    const storedLanguage = await AsyncStorage.getItem(LANGUAGE_PREFERENCE);
    if (storedLanguage) {
      language = storedLanguage;
    }
  } catch (error) {
    console.error('Error reading language from AsyncStorage', error);
  }

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

  // Set moment locale
  moment.locale(language);

  // Update moment locale on language change
  i18n.on('languageChanged', (lng) => {
    moment.locale(lng);
  });
};

export { initI18n };
export default i18n;{
  "appTitle": "HistoryGPT",
  "homeScreen": {
    "title": "Tarihi Karakterler",
    "errorLoadingFigures": "Figürler yüklenirken bir hata oluştu.",
    "startChat": "Sohbete Başla"
  },
  "chatListScreen": {
    "title": "Sohbetlerim",
    "noChats": "Hiç sohbetiniz yok! Yeni bir sohbet başlatın.",
    "deleteAllChatsTitle": "Tüm Sohbetleri Sil",
    "deleteAllChatsMessage": "{{count}} sohbet silinecek. Emin misiniz?",
    "deleteChatConfirmation": "Bu sohbeti silmek istediğinizden emin misiniz?",
    "deleteChatYes": "Sil",
    "deleteChatNo": "İptal",
    "errorLoadingChats": "Sohbetler yüklenirken bir hata oluştu.",
    "errorDeletingChat": "Sohbet silinirken bir hata oluştu.",
    "errorDeletingAllChats": "Sohbetler silinirken bir hata oluştu."
  },
  "chatScreen": {
    "placeholder": "Mesajınızı yazın...",
    "send": "Gönder",
    "timeAgo": "{{time}} önce"
  },
  "settings": {
    "title": "Ayarlar",
    "language": "Dil",
    "theme": "Tema",
    "english": "İngilizce",
    "turkish": "Türkçe",
    "light": "Açık",
    "dark": "Koyu",
    "system": "Sistem"
  }
}
{
  "appTitle": "HistoryGPT",
  "homeScreen": {
    "title": "Historical Figures",
    "errorLoadingFigures": "Error loading figures.",
    "startChat": "Start Chat"
  },
  "chatListScreen": {
    "title": "My Chats",
    "noChats": "You have no chats yet! Start a new chat.",
    "deleteAllChatsTitle": "Delete All Chats",
    "deleteAllChatsMessage": "{{count}} chats will be deleted. Are you sure?",
    "deleteChatConfirmation": "Are you sure you want to delete this chat?",
    "deleteChatYes": "Delete",
    "deleteChatNo": "Cancel",
    "errorLoadingChats": "Error loading chats.",
    "errorDeletingChat": "Error deleting chat.",
    "errorDeletingAllChats": "Error deleting all chats."
  },
  "chatScreen": {
    "placeholder": "Type your message...",
    "send": "Send",
    "timeAgo": "{{time}} ago"
  },
  "settings": {
    "title": "Settings",
    "language": "Language",
    "theme": "Theme",
    "english": "English",
    "turkish": "Turkish",
    "light": "Light",
    "dark": "Dark",
    "system": "System"
  }
}
// src/i18n/constants.ts
export const LANGUAGE_PREFERENCE = 'user-language';
diğer hata da şu:
error loading messages: reference error property asyncstore doesnt exist:
// src/screens/ChatScreen.tsx

import React, { useState, useEffect, useRef, useCallback, useContext } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  TextInput, 
  StyleSheet, 
  KeyboardAvoidingView, 
  Platform,
  Dimensions,
  ScrollView,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import LottieView from 'lottie-react-native';
import { Message, HistoricalFigure } from '../types/types';
import { fetchAIResponse } from '../services/openaiService';
import uuid from 'react-native-uuid';
import MessageItem from '../components/MessageItem';
import { Ionicons } from '@expo/vector-icons';
import CustomText from '../components/CustomText';
import * as Clipboard from 'expo-clipboard';
import { ChatContext } from '../context/ChatContext';
import { ThemeContext } from '../theme/ThemeContext';
import { useTranslation } from 'react-i18next';
import moment from 'moment';
import 'moment/locale/tr'; // veya diğer diller için

interface RouteParams {
  chatId: string;
  figure: HistoricalFigure;
}

interface APIMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

const { width, height } = Dimensions.get('window');

const ChatScreen = () => {
  const navigation = useNavigation();
  const route = useRoute();
  const { t } = useTranslation();
  const { chatId, figure } = route.params as RouteParams;
  const { addChat, updateChat } = useContext(ChatContext);
  const { themeObject } = useContext(ThemeContext);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState<string>('');
  const [isTyping, setIsTyping] = useState<boolean>(false);
  const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const flatListRef = useRef<FlatList>(null);

  const sampleFollowUpQuestions = [
    'Would you like to learn more details about this?',
    'What else would you like to talk about?',
    'Do you want a different perspective?',
  ];

  useEffect(() => {
    const loadMessages = async () => {
      try {
        setIsLoading(true);
        setMessages([]);
        setFollowUpQuestions([]);
        setIsTyping(false);

        const messagesData = await AsyncStorage.getItem(`chat_${chatId}_messages`);
        let msgs: Message[] = messagesData ? JSON.parse(messagesData) : [];

        if (msgs.length === 0) {
          const conversationStarters = [
            'Hello! How can I assist you today?',
            `What would you like to learn about ${figure.name}?`,
            `Do you have any questions about ${figure.name}?`
          ];

          const starterMessages = conversationStarters.map((starter) => ({
            id: uuid.v4().toString(),
            text: starter,
            isUser: false,
            timestamp: Date.now(),
          }));

          msgs = starterMessages;
          await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(msgs));
        }

        setMessages(msgs);
        setIsLoading(false);

        setTimeout(() => {
          flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
        }, 100);
      } catch (error) {
        console.error('Error loading messages:', error);
        setIsLoading(false);
      }
    };

    loadMessages();
  }, [chatId, figure.name]);

  const saveMessages = useCallback(async (updatedMessages: Message[]) => {
    try {
      await AsyncStorage.setItem(`chat_${chatId}_messages`, JSON.stringify(updatedMessages));
    } catch (error) {
      console.error('Error saving messages:', error);
    }
  }, [chatId]);

  const generateFollowUpQuestions = useCallback(async (aiResponse: string) => {
    try {
      const prompt = `Based on the AI response below, generate only three follow-up questions. Only questions should be present, without explanatory text or additional information.\n\nResponse: "${aiResponse}"\n\nFollow-Up Questions:`;
      const aiMessages: APIMessage[] = [
        {
          role: 'system',
          content: 'You are a helpful and informative AI assistant.'
        },
        {
          role: 'user',
          content: prompt
        }
      ];

      const followUpResponse = await fetchAIResponse(aiMessages);
      const rawQuestions = followUpResponse.split('\n').map(q => q.trim()).filter(q => q.length > 0).slice(0, 3);

      const cleanQuestion = (question: string) => {
        return question.replace(/^\d+\.\s*/, '');
      };

      const cleanedQuestions = rawQuestions.map(cleanQuestion);

      if (cleanedQuestions.length < 3) {
        setFollowUpQuestions([...cleanedQuestions, ...sampleFollowUpQuestions.slice(0, 3 - cleanedQuestions.length)]);
      } else {
        setFollowUpQuestions(cleanedQuestions);
      }
    } catch (error) {
      console.error('Error generating follow-up questions:', error);
      setFollowUpQuestions(sampleFollowUpQuestions);
    }
  }, []);

  const sendMessage = useCallback(async (text?: string) => {
    const messageText = text !== undefined ? text : inputText;
    if (messageText.trim() === '') return;

    const userMessage: Message = {
      id: uuid.v4().toString(),
      text: messageText,
      isUser: true,
      timestamp: Date.now(),
    };

    const updatedMessages = [userMessage, ...messages];
    setMessages(updatedMessages);
    setInputText('');
    setIsTyping(true);
    setFollowUpQuestions([]);

    await saveMessages(updatedMessages);
    await updateChat(chatId, userMessage);

    const apiMessages: APIMessage[] = [
      {
        role: 'system',
        content: figure.systemPrompt,
      },
      ...updatedMessages
        .slice()
        .reverse()
        .map(msg => ({
          role: msg.isUser ? 'user' : 'assistant',
          content: msg.text,
        })),
    ];

    console.log('==== Sending Messages to AI ====');
    apiMessages.forEach((msg, index) => {
      console.log(`Message ${index + 1}: [${msg.role}] ${msg.content}`);
    });
    console.log('===============================');

    try {
      const aiResponse = await fetchAIResponse(apiMessages);

      const aiMessage: Message = {
        id: uuid.v4().toString(),
        text: aiResponse,
        isUser: false,
        timestamp: Date.now(),
      };

      const newMessages = [aiMessage, ...updatedMessages];
      setMessages(newMessages);
      await saveMessages(newMessages);
      await updateChat(chatId, aiMessage);

      await generateFollowUpQuestions(aiResponse);
    } catch (error) {
      console.error('Error fetching AI response:', error);
      Alert.alert(t('chatScreen.errorFetchingAI'));
    } finally {
      setIsTyping(false);
      flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
    }
  }, [inputText, messages, figure.systemPrompt, saveMessages, generateFollowUpQuestions, chatId, updateChat, t]);

  const handleFollowUpPress = (question: string) => {
    sendMessage(question);
  };

  const renderMessageItem = useCallback(({ item }: { item: Message }) => (
    <MessageItem 
      message={item} 
      onLongPress={() => {
        Clipboard.setString(item.text);
        Alert.alert(t('copied'), t('chatScreen.copiedToClipboard'));
      }}
    />
  ), [t]);

  const keyExtractor = useCallback((item: Message) => item.id, []);

  useEffect(() => {
    if (messages.length > 0) {
      flatListRef.current?.scrollToOffset({ animated: true, offset: 0 });
    }
  }, [messages]);

  return (
    <KeyboardAvoidingView
      style={[styles.container, { backgroundColor: themeObject.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
    >
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backButton}>
          <Ionicons name="arrow-back" size={28} color={themeObject.text} />
        </TouchableOpacity>
        <Image source={{ uri: figure.image }} style={styles.headerAvatar} />
        <View style={styles.headerInfo}>
          <CustomText bold style={[styles.headerName, { color: themeObject.text }]}>{figure.name}</CustomText>
          <CustomText style={[styles.headerDescription, { color: themeObject.text }]} numberOfLines={1}>
            {figure.description}
          </CustomText>
        </View>
      </View>

      {isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#007AFF" />
        </View>
      ) : (
        <FlatList
          ref={flatListRef}
          data={messages}
          renderItem={renderMessageItem}
          keyExtractor={keyExtractor}
          style={styles.messageList}
          contentContainerStyle={styles.messageListContent}
          inverted
        />
      )}

      {isTyping && (
        <View style={styles.typingIndicator}>
          <LottieView
            source={require('../../assets/typing-animation.json')}
            autoPlay
            loop
            style={styles.typingAnimation}
          />
        </View>
      )}

      {followUpQuestions.length > 0 && (
        <View style={styles.followUpContainer}>
          <CustomText bold style={[styles.followUpTitle, { color: themeObject.text }]}>{t('chatScreen.followUpQuestions')}</CustomText>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            {followUpQuestions.map((question, index) => (
              <TouchableOpacity 
                key={index} 
                style={[styles.followUpButton, { backgroundColor: '#E0E0E0' }]} 
                onPress={() => handleFollowUpPress(question)}
              >
                <CustomText style={[styles.followUpText, { color: themeObject.text }]}>{question}</CustomText>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      )}

      <View style={styles.inputContainer}>
        <TextInput
          style={[
            styles.input, 
            { backgroundColor: themeObject.chatBubbleAssistant, color: themeObject.text }
          ]}
          value={inputText}
          onChangeText={setInputText}
          placeholder={t('chatScreen.placeholder')}
          placeholderTextColor="#999"
          onSubmitEditing={() => sendMessage()}
          returnKeyType="send"
        />
        <TouchableOpacity onPress={() => sendMessage()} style={styles.sendButton}>
          <Ionicons name="send" size={24} color="#fff" />
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    paddingTop: Platform.OS === 'ios' ? 50 : 30,
    borderBottomWidth: 1,
  },
  backButton: {
    marginRight: 10,
  },
  headerAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
  },
  headerInfo: {
    flex: 1,
  },
  headerName: {
    fontSize: 18,
    fontFamily: 'Poppins_700Bold',
  },
  headerDescription: {
    fontSize: 14,
    marginTop: 2,
    fontFamily: 'Poppins_400Regular',
  },
  messageList: {
    flex: 1,
  },
  messageListContent: {
    paddingVertical: 10,
    paddingHorizontal: 15,
  },
  typingIndicator: {
    position: 'absolute',
    bottom: 70,
    left: 20,
  },
  typingAnimation: {
    width: 80,
    height: 40,
  },
  followUpContainer: {
    padding: 10,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E0E0E0',
  },
  followUpTitle: {
    fontSize: 16,
    marginBottom: 5,
    fontFamily: 'Poppins_700Bold',
  },
  followUpButton: {
    borderRadius: 15,
    paddingVertical: 8,
    paddingHorizontal: 12,
    marginRight: 10,
  },
  followUpText: {
    fontSize: 14,
    fontFamily: 'Poppins_400Regular',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E0E0E0',
  },
  input: {
    flex: 1,
    height: 40,
    borderRadius: 20,
    paddingHorizontal: 15,
    marginRight: 10,
    fontFamily: 'Poppins_400Regular',
  },
  sendButton: {
    backgroundColor: '#007AFF',
    borderRadius: 20,
    padding: 10,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default ChatScreen;