// src/screens/HomeScreen.tsx

import React, { useCallback, useContext, useState, useEffect } from 'react';
import { 
  View, 
  FlatList, 
  Image, 
  TouchableOpacity, 
  StyleSheet, 
  SafeAreaView,
  useWindowDimensions,
  RefreshControl,
  ScrollView,
  Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigureLocalized } from '../types/types'; // Updated import
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid'; // Ensure correct import
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomeScreen = () => {
  const navigation = useNavigation();
  const { 
    historicalFigures, 
    refreshing, 
    t, 
    currentTheme, 
    refreshFigures,
    categories,
  } = useApp();
  const { width } = useWindowDimensions();

  const { addChat } = useContext(ChatContext);
  const { coins, showRewardedAd } = useContext(CoinContext);
  const [selectedCategory, setSelectedCategory] = useState<string>(t('all'));

  const numColumns = 2;

  const startChat = useCallback(async (figure: HistoricalFigureLocalized) => {
    try {
      const chatId = uuid.v4().toString();
      console.log('Generated chatId:', chatId); // Logging for debugging

      await addChat({
        id: chatId,
        figure,
        createdAt: Date.now(),
      });

      navigation.navigate('Chat', { chatId, figure });
    } catch (error) {
      console.error('Error starting chat:', error);
      Alert.alert(t('error'), t('errorStartingChat'));
    }
  }, [addChat, navigation, t]);

  const renderFigureItem = useCallback(({ item }: { item: HistoricalFigureLocalized }) => (
    <TouchableOpacity
      style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
      onPress={() => startChat(item)}
    >
      <Image source={{ uri: item.image }} style={styles.avatar} />
      <View style={styles.figureTextContainer}>
        <CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
          {item.name}
        </CustomText>
        <CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
          {item.category}
        </CustomText>
        <CustomText 
          style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]} 
          numberOfLines={3}
        >
          {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: HistoricalFigureLocalized) => item.id, []);

  const onRefresh = useCallback(async () => {
    await refreshFigures(); // This will handle refreshing state in AppContext
  }, [refreshFigures]);

  const filteredFigures = selectedCategory === t('all') 
    ? historicalFigures 
    : historicalFigures.filter(fig => fig.category === selectedCategory);

  const renderCategoryItem = useCallback((category: string, index: number) => {
    const isSelected = category === selectedCategory;
    return (
      <TouchableOpacity
        key={`${category}-${index}`} // Ensure each item has a unique key
        style={[
          styles.categoryButton,
          { 
            backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
            borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
          }
        ]}
        onPress={() => setSelectedCategory(category)}
      >
        <CustomText 
          style={[
            styles.categoryText, 
            { 
              color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
            }
          ]}
        >
          {category}
        </CustomText>
      </TouchableOpacity>
    );
  }, [selectedCategory, currentTheme]);

  const renderCategoryRows = () => {
    // Display categories in two rows for better organization
    const halfLength = Math.ceil(categories.length / 2);
    return (
      <ScrollView 
        horizontal 
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.categoryRowsContainer}
      >
        <View>
          <View style={styles.categoryRow}>
            {categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
          </View>
          <View style={styles.categoryRow}>
            {categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
          </View>
        </View>
      </ScrollView>
    );
  };

  // Debugging Effect: Log filtered figures and selected category
  useEffect(() => {
    console.log(`Selected Category: ${selectedCategory}`);
    console.log('Filtered Figures:', filteredFigures);
  }, [selectedCategory, filteredFigures]);

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
      <StatusBar style={currentTheme.statusBarStyle} />
      <View style={styles.container}>
        {/* Header */}
        <View style={styles.header}>
          <CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
            {t('historicalFigures')}
          </CustomText>
          <View style={styles.headerRight}>
            {/* Coin Display */}
            <TouchableOpacity style={styles.coinContainer} onPress={showRewardedAd}>
              <Ionicons name="flash" size={20} color={currentTheme.accentColor} />
              <CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
                {coins}
              </CustomText>
            </TouchableOpacity>
            {/* Settings Button */}
            <TouchableOpacity 
              style={styles.settingsButton} 
              onPress={() => navigation.navigate('Settings')}
            >
              <Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
            </TouchableOpacity>
          </View>
        </View>

        {/* Category Selector (Two Rows, Scrollable Horizontally) */}
        {renderCategoryRows()}

        {/* Content */}
        {filteredFigures.length === 0 ? (
          <View style={styles.emptyContainer}>
            <CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
              {t('noFiguresInThisCategory')}
            </CustomText>
          </View>
        ) : (
          <FlatList
            data={filteredFigures}
            renderItem={renderFigureItem}
            keyExtractor={keyExtractor}
            contentContainerStyle={styles.figureList}
            numColumns={numColumns}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={[currentTheme.accentColor]}
                tintColor={currentTheme.accentColor}
              />
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
  },
  container: {
    flex: 1,
    paddingHorizontal: 10,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 15,
    paddingHorizontal: 15,
  },
  title: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 24,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  coinContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 5,
  },
  coinText: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 18,
    marginLeft: 5,
  },
  settingsButton: {
    padding: 2,
    marginLeft: 15, // Increased spacing for better visual separation
  },
  categoryRowsContainer: {
    paddingHorizontal: 5,
    paddingBottom: 20,
  },
  categoryRow: {
    flexDirection: 'row',
    marginBottom: 6,
  },
  categoryButton: {
    paddingVertical: 8,
    paddingHorizontal: 10, // Increased padding for better touch area
    borderRadius: 16,
    borderWidth: 1,
    marginRight: 5, // Increased margin for better spacing
  },
  categoryText: {
    fontFamily: 'Poppins_600SemiBold',
    fontSize: 14,
  },
  figureList: {
    paddingVertical: 10,
  },
  figureItem: {
    borderRadius: 12,
    elevation: 3,
    flex: 1,
    margin: 5,
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
    shadowColor: '#000',
  },
  avatar: {
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    height: 120, // Uniform height across all images
    width: '100%', // Span the full width of the figure item
    resizeMode: 'cover', // Cover ensures the image fills the space without distortion
  },
  figureTextContainer: {
    padding: 10,
  },
  figureName: {
    fontFamily: 'Poppins_700Bold',
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 4,
  },
  figureCategory: {
    fontFamily: 'Poppins_600SemiBold',
    textAlign: 'center',
    fontSize: 12,
    marginBottom: 4,
  },
  figureDescription: {
    fontFamily: 'Poppins_400Regular',
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 4,
  },
  popularity: {
    textAlign: 'center',
    fontSize: 14,
    fontFamily: 'Poppins_600SemiBold',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    fontSize: 16,
    textAlign: 'center',
  },
});

export default HomeScreen; bu kodu incele bunu da incele // src/context/AppContext.tsx

import React, {
  createContext,
  useState,
  useContext,
  useEffect,
  useCallback,
  ReactNode,
} from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { translations, Theme, themes } from './config';
import { HistoricalFigure, HistoricalFigureLocalized } from '../types/types';
import { db } from '../services/firebaseConfig';
import {
  collection,
  getDocs,
  doc,
  updateDoc,
  increment,
} from 'firebase/firestore';
import { Alert } from 'react-native';

// Define supported languages and themes
type Language = 'en' | 'tr';
type ThemeType = 'light' | 'dark';

// Define the shape of the context
interface AppContextType {
  language: Language;
  theme: ThemeType;
  toggleTheme: () => void;
  changeLanguage: (lang: Language) => void;
  t: (key: string) => string;
  currentTheme: Theme;
  historicalFigures: HistoricalFigureLocalized[];
  loading: boolean;
  refreshing: boolean;
  loadFigures: () => Promise<void>;
  refreshFigures: () => Promise<void>;
  incrementPopularity: (figureId: string) => Promise<void>;
  categories: string[];
}

// Define a localized version of HistoricalFigure
interface HistoricalFigureLocalized {
  id: string;
  name: string;
  image: string;
  systemPrompt: string;
  description: string;
  ai: string;
  starterQuestions: string[];
  category: string;
  popularity: number;
}

// Create the context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Define storage keys and cache duration
const STORAGE_KEY_FIGURES = 'historical_figures';
const STORAGE_KEY_FIGURES_TIMESTAMP = 'historical_figures_timestamp';
const STORAGE_KEY_LANGUAGE = 'language';
const STORAGE_KEY_THEME = 'theme';
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 1 day in milliseconds

// Create the provider component
export const AppProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  // State variables
  const [language, setLanguage] = useState<Language>('en');
  const [theme, setTheme] = useState<ThemeType>('light');
  const [historicalFiguresRaw, setHistoricalFiguresRaw] = useState<HistoricalFigure[]>([]);
  const [historicalFigures, setHistoricalFigures] = useState<HistoricalFigureLocalized[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const [categories, setCategories] = useState<string[]>([]);

  /**
   * Helper function to map raw historical figures to localized figures based on current language.
   */
  const mapFiguresToLanguage = useCallback((figures: HistoricalFigure[], lang: Language): HistoricalFigureLocalized[] => {
    return figures.map(fig => ({
      id: fig.id,
      name: lang === 'tr' ? (fig.nameTR || fig.nameEN || 'Unnamed') : (fig.nameEN || fig.nameTR || 'Unnamed'),
      image: fig.image,
      systemPrompt: lang === 'tr' ? (fig.systemPromptTR || fig.systemPromptEN || '') : (fig.systemPromptEN || fig.systemPromptTR || ''),
      description: lang === 'tr' ? (fig.descriptionTR || fig.descriptionEN || '') : (fig.descriptionEN || fig.descriptionTR || ''),
      ai: fig.ai || 'openai',
      starterQuestions: fig.starterQuestions || [],
      category: lang === 'tr' ? (fig.categoryTR || fig.categoryEN || 'Kategori Yok') : (fig.categoryEN || fig.categoryTR || 'Uncategorized'),
      popularity: fig.popularity || 0,
    }));
  }, []);

  /**
   * Load language and theme settings from AsyncStorage on mount.
   */
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const [storedLanguage, storedTheme] = await Promise.all([
          AsyncStorage.getItem(STORAGE_KEY_LANGUAGE),
          AsyncStorage.getItem(STORAGE_KEY_THEME),
        ]);

        // Set language to 'tr' if stored as 'tr', otherwise default to 'en'
        if (storedLanguage === 'tr') {
          setLanguage('tr');
        } else {
          setLanguage('en');
        }

        // Similarly, set the theme if stored
        if (storedTheme === 'light' || storedTheme === 'dark') {
          setTheme(storedTheme);
        } else {
          setTheme('light'); // default theme
        }
      } catch (error) {
        console.error('Error loading settings:', error);
      }
    };

    loadSettings();
  }, []);

  /**
   * Effect to map raw historical figures to localized figures whenever raw data or language changes.
   */
  useEffect(() => {
    if (historicalFiguresRaw.length > 0) {
      const localizedFigures = mapFiguresToLanguage(historicalFiguresRaw, language);
      setHistoricalFigures(localizedFigures);
      extractCategories(historicalFiguresRaw, language);
    }
  }, [historicalFiguresRaw, language, mapFiguresToLanguage]);

  /**
   * Function to toggle between light and dark themes
   */
  const toggleTheme = () => {
    const newTheme: ThemeType = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    AsyncStorage.setItem(STORAGE_KEY_THEME, newTheme).catch((err) =>
      console.error('Error saving theme:', err)
    );
  };

  /**
   * Function to change the language
   */
  const changeLanguage = (lang: Language) => {
    const newLanguage: Language = lang === 'tr' ? 'tr' : 'en';
    setLanguage(newLanguage);
    AsyncStorage.setItem(STORAGE_KEY_LANGUAGE, newLanguage).catch((err) =>
      console.error('Error saving language:', err)
    );
  };

  /**
   * Translation function based on the current language
   */
  const t = (key: string): string => {
    return translations[language][key] || key;
  };

  /**
   * Function to load historical figures.
   * It first attempts to load from cache (AsyncStorage).
   * If cache is invalid or absent, it fetches from Firebase.
   */
  const loadFigures = useCallback(async () => {
    setLoading(true);
    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);
        figuresList.sort((a, b) => (b.popularity || 0) - (a.popularity || 0));
        setHistoricalFiguresRaw(figuresList);
      } else {
        await fetchFiguresFromFirebase();
      }
    } catch (error) {
      console.error('Error loading figures:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
    } finally {
      setLoading(false);
    }
  }, [t]);

  /**
   * Function to fetch historical figures from Firebase.
   * It updates both the state and the cache.
   */
  const fetchFiguresFromFirebase = useCallback(async () => {
    try {
      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,
          nameTR: data.nameTR,
          nameEN: data.nameEN,
          image: data.image,
          systemPromptTR: data.systemPromptTR,
          systemPromptEN: data.systemPromptEN,
          descriptionTR: data.descriptionTR,
          descriptionEN: data.descriptionEN,
          ai: data.ai || 'openai',
          starterQuestions: data.starterQuestions || [],
          categoryTR: data.categoryTR,
          categoryEN: data.categoryEN,
          popularity: data.popularity || 0,
        } as HistoricalFigure;
      });

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

      setHistoricalFiguresRaw(figuresList);

      const now = Date.now();
      await AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(figuresList));
      await AsyncStorage.setItem(STORAGE_KEY_FIGURES_TIMESTAMP, now.toString());
    } catch (error) {
      console.error('Error fetching figures from Firebase:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
      throw error; // Re-throw to allow caller to handle if needed
    }
  }, [t]);

  /**
   * Function to refresh historical figures.
   * It fetches fresh data from Firebase regardless of the cache.
   */
  const refreshFigures = useCallback(async () => {
    setRefreshing(true);
    try {
      await fetchFiguresFromFirebase();
    } catch (error) {
      console.error('Error refreshing figures:', error);
      Alert.alert(t('error'), t('errorLoadingFigures'));
    } finally {
      setRefreshing(false);
    }
  }, [fetchFiguresFromFirebase, t]);

  /**
   * Function to increment the popularity of a specific historical figure.
   * It updates both the local state and Firebase.
   */
  const incrementPopularity = useCallback(
    async (figureId: string) => {
      // Update local state optimistically
      setHistoricalFiguresRaw((prevFigures) => {
        const updatedFigures = prevFigures.map((fig) => {
          if (fig.id === figureId) {
            return {
              ...fig,
              popularity: (fig.popularity || 0) + 1,
            };
          }
          return fig;
        });

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

        // Update the cache with the new figures list
        AsyncStorage.setItem(STORAGE_KEY_FIGURES, JSON.stringify(updatedFigures)).catch(
          (err) => console.error('Error saving figures:', err)
        );

        return updatedFigures;
      });

      // Update popularity in Firebase
      try {
        const figureDocRef = doc(db, 'figures', figureId);
        await updateDoc(figureDocRef, {
          popularity: increment(1),
        });
      } catch (error) {
        console.error('Error updating popularity in Firebase:', error);
        // Optional: Revert the local state change if Firebase update fails
      }
    },
    []
  );

  /**
   * Function to extract unique categories from the list of historical figures.
   * It ensures 'All' is always the first category and uses the current language for category names.
   */
  const extractCategories = useCallback((figures: HistoricalFigure[], lang: Language) => {
    const allCategoriesSet = new Set<string>(
      figures.map((fig) =>
        lang === 'tr'
          ? fig.categoryTR || fig.categoryEN || 'Kategori Yok'
          : fig.categoryEN || fig.categoryTR || 'Uncategorized'
      )
    );
    const allCategories = Array.from(allCategoriesSet).sort(); // Optional: sort categories

    // Ensure 'All' is not duplicated
    const uniqueCategories = allCategories.filter(
      (category) => category !== t('all')
    );

    setCategories([t('all'), ...uniqueCategories]);
  }, [t]);

  // Define the context value
  const value: AppContextType = {
    language,
    theme,
    toggleTheme,
    changeLanguage,
    t,
    currentTheme: themes[theme],
    historicalFigures,
    loading,
    refreshing,
    loadFigures,
    refreshFigures,
    incrementPopularity,
    categories,
  };

  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};

// Custom hook to use the AppContext
export const useApp = (): AppContextType => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
};

// Utility function to access the current language outside React components
export const getCurrentLanguage = async (): Promise<Language> => {
  try {
    const storedLanguage = (await AsyncStorage.getItem(STORAGE_KEY_LANGUAGE)) as Language | null;
    return storedLanguage === 'tr' ? 'tr' : 'en';
  } catch (error) {
    console.error('Error getting current language:', error);
    return 'en'; // default to 'en' in case of error
  }
};bu şekilde bir log giriliyor consoleye:
Android Bundled 60846ms node_modules/expo/AppEntry.js (1418 modules)
 LOG  Selected Category: all
 LOG  Filtered Figures: []


oysa ki firebasede böyle bir figürümüz kayıtlı.
{
  "ai": "openai",
  "categoryEN": "historical",
  "categoryTR": "tarihsel",
  "descriptionEN": "I’m Necmi Abi, an old-world barber in 2098,.",
  "descriptionTR": "Ben Necmi Abi, i",
  "image": "https://image.pollinations.ai/prompt/alien%20barber%20shop%20with%20turkish%20character%20necmi%20abi",
  "nameEN": "Barber in Space",
  "nameTR": "Necmi Abi",
  "popularity": 70,
  "systemPromptEN": "YOU ARE NECMI ABI,",
"systemPromptTR": "SEN NECMİ ABİ'SİN,"
}

hatayı bulur musun? neden ana sayfada nofiguresinthiscategory yazısını görüyorum?