başka bir sayfadan buraya her girildiğinde sayfayı yeniliyor. bunu yapmasın. ve loading ikonları her bir figürün her bir adı, descriptionu ve popularity değeri için dönüyor. bu da olmasın. // src/screens/HomeScreen.tsx

import React, { useEffect, useState, useCallback, useContext } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  Alert,
  SafeAreaView,
  Platform,
  StatusBar as RNStatusBar,
  ActivityIndicator,
  useWindowDimensions,
  RefreshControl
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure, Chat, Message } from '../types/types';
import { db } from '../services/firebaseConfig';
import { collection, getDocs, query, orderBy } from 'firebase/firestore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';

const STORAGE_KEY_FIGURES = 'historical_figures';
const STORAGE_KEY_FIGURES_TIMESTAMP = 'historical_figures_timestamp';
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 1 day in milliseconds

const HomeScreen = () => {
  const navigation = useNavigation();
  const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigure[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [refreshing, setRefreshing] = useState<boolean>(false); // Add refreshing state
  const { width } = useWindowDimensions();
  const { t, currentTheme } = useApp(); // Existing useApp hook

  // Import addChat from ChatContext
  const { addChat } = useContext(ChatContext);

  // Set numColumns to 2 for two-column grid
  const numColumns = 2;

  useEffect(() => {
    const loadFigures = async () => {
      try {
        const [cachedFigures, cachedTimestamp] = await Promise.all([
          AsyncStorage.getItem(STORAGE_KEY_FIGURES),
          AsyncStorage.getItem(STORAGE_KEY_FIGURES_TIMESTAMP),
        ]);

        const now = Date.now();
        const isCacheValid = cachedFigures && cachedTimestamp && (now - parseInt(cachedTimestamp, 10) < CACHE_DURATION);

        if (isCacheValid) {
          const figuresList: HistoricalFigure[] = JSON.parse(cachedFigures);
          // Sort figures by popularity descending
          figuresList.sort((a, b) => (b.popularity || 0) - (a.popularity || 0));
          setHistoricalFigures(figuresList);
        } else {
          await fetchFiguresFromFirebase();
        }
      } catch (error) {
        console.error('Error loading figures:', error);
        Alert.alert(t('error'), t('errorLoadingFigures'));
      } finally {
        setLoading(false);
      }
    };

    loadFigures();
  }, [t]);

  // Function to fetch figures from Firebase and update cache
  const fetchFiguresFromFirebase = async () => {
    try {
      // Eğer sıralama yapmak istiyorsanız Firestore'da orderBy kullanabilirsiniz
      // Ancak, AsyncStorage'a kaydetmeden önce tekrar sıralamak için burada sıralayacağız
      const figuresCollection = collection(db, 'figures');
      const figuresSnapshot = await getDocs(figuresCollection);
      const figuresList: HistoricalFigure[] = figuresSnapshot.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          name: data.name,
          image: data.image,
          systemPrompt: data.systemPrompt,
          description: data.description || "",
          ai: data.ai || "openai", // Default to "openai" if "ai" is not provided
          starterQuestions: data.starterQuestions || [], // Default to empty array if not provided
          popularity: data.popularity || 0, // Default to 0 if not provided
        } as HistoricalFigure;
      });

      // Sort figures by popularity descending
      figuresList.sort((a, b) => (b.popularity || 0) - (a.popularity || 0));

      setHistoricalFigures(figuresList);
      const now = Date.now();
      await Promise.all([
        AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(figuresList)),
        AsyncStorage.setItem(STORAGE_KEY_FIGURES_TIMESTAMP, now.toString()),
      ]);
    } catch (error) {
      console.error('Error fetching figures:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
    }
  };

  // Function to start a chat, updated to use addChat from ChatContext
  const startChat = async (figure: HistoricalFigure) => {
    const chatId = uuid.v4().toString();
    const newChat: Chat = {
      id: chatId,
      figure: {
        ...figure,
        description: figure.description || "",
      },
      createdAt: Date.now(),
    };

    const initialMessage: Message = {
      id: uuid.v4().toString(),
      text: figure.description || t('noDescriptionAvailable'),
      isUser: false,
      timestamp: Date.now(),
    };

    try {
      // Add chat using ChatContext
      await addChat(newChat, [initialMessage]);

      console.log('Chat added:', newChat);
      console.log('Initial message added:', initialMessage);

      // Navigate to Chat screen
      navigation.navigate('Chat', { chatId, figure });
    } catch (error) {
      console.error('Error starting chat:', error);
      Alert.alert(t('error'), t('errorStartingChat'));
    }
  };

  // Render each figure item
  const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
    <TouchableOpacity
      style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
      onPress={() => startChat(item)}
    >
      <Image source={{ uri: item.image }} style={styles.avatar} />
      <View style={styles.figureInfo}>
        <CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>{item.name}</CustomText>
        <CustomText style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]} numberOfLines={2}>
          {item.description}
        </CustomText>
        <CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
          {t('popularity')}: {item.popularity || 0}
        </CustomText>
      </View>
    </TouchableOpacity>
  ), [currentTheme, startChat, t]);

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

  // Function to handle pull-to-refresh
  const onRefresh = useCallback(async () => {
    setRefreshing(true); // Start refreshing
    try {
      await fetchFiguresFromFirebase(); // Re-fetch data from Firebase
    } catch (error) {
      console.error('Error refreshing figures:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
    } finally {
      setRefreshing(false); // Stop refreshing
    }
  }, [t]);

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
      <StatusBar style={currentTheme.statusBarStyle} />
      <View style={styles.container}>
        <View style={styles.header}>
          <CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>{t('historicalFigures')}</CustomText>
          <TouchableOpacity 
            style={styles.settingsButton} 
            onPress={() => navigation.navigate('Settings')}
          >
            <Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
          </TouchableOpacity>
        </View>
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={currentTheme.accentColor} />
          </View>
        ) : (
          <FlatList
            data={historicalFigures}
            renderItem={renderFigureItem}
            keyExtractor={keyExtractor}
            contentContainerStyle={styles.figureList}
            numColumns={numColumns}
            key={numColumns.toString()}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing} // Bind refreshing state
                onRefresh={onRefresh} // Bind onRefresh function
                colors={[currentTheme.accentColor]} // Optional: Customize the color
                tintColor={currentTheme.accentColor} // For iOS
              />
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  avatar: {
    borderRadius: 30,
    height: 100,
    width: 100,
    alignSelf: 'center',
    marginBottom: 10,
  },
  container: {
    flex: 1,
    paddingHorizontal: 10,
  },
  figureDescription: {
    fontFamily: 'Poppins_400Regular',
    fontSize: 12,
    marginTop: 4,
    textAlign: 'center',
  },
  figureInfo: {
    alignItems: 'center',
    flex: 1,
    paddingHorizontal: 5,
  },
  figureItem: {
    borderRadius: 12,
    elevation: 3,
    flex: 1,
    margin: 5,
    padding: 10,
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
    shadowColor: '#000',
  },
  figureList: {
    paddingVertical: 10,
  },
  figureName: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 14,
    textAlign: 'center',
  },
  header: {
    alignItems: 'center',
    borderBottomWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 15,
    paddingHorizontal: 15,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  safeArea: {
    flex: 1,
  },
  settingsButton: {
    padding: 5,
  },
  title: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 24,
  },
  popularity: {
    fontSize: 14,
    marginTop: 4,
  },
});

export default HomeScreen;