import React, { useState, useCallback, useRef } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  Image,
  Text,
  ActivityIndicator,
  TouchableOpacity,
  Dimensions,
  StatusBar,
  I18nManager,
} from 'react-native';
import Popover, { Rect } from 'react-native-popover-view';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext';
import { CustomTextB, CustomTextR } from '../components/CustomText';
import { LinearGradient } from 'expo-linear-gradient';

import translateIcon from '../../assets/translate2.png';

const GOOGLE_TRANSLATE_LOGO = require('../../assets/googletranslate.png');
const CHATGPT_LOGO = require('../../assets/chatgpt.png');

import translate from 'translate-google-api';

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

const RSSReadScreen = ({ route }) => {
  const { item } = route.params;
  const { theme, t, locale, arabicFont, arabicFontBold } = useThemeAndLanguage();
  const [selectedText, setSelectedText] = useState('');
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [translation, setTranslation] = useState('');
  const [translationSource, setTranslationSource] = useState(null);
  const [loading, setLoading] = useState(false);
  const [rect, setRect] = useState(new Rect(0, 0, 0, 0));
  const scrollViewRef = useRef(null);
  const measuringInProgress = useRef(false);
  const popoverContentHeight = useRef(0);
  const currentSentenceRef = useRef('');

  const getTranslation = useCallback(async (text, isWord = true) => {
    setLoading(true);
    setTranslationSource('ai');
    try {
      const systemPrompt = locale === 'tr' 
        ? "Sen bir Arapça-Türkçe çevirmenisin. Sadece çeviriyi ver, başka bir şey yazma. kelimenin birden fazla anlamı varsa onları da yazabilirsin, 1 2 3 şeklinde sıralayarak."
        : "You are an Arabic-English translator. Provide only the translation, nothing else. If the word has multiple meanings, you can list them as 1 2 3.";

      const response = await fetch('https://text.pollinations.ai/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: text }
          ],
          model: "openai",
          seed: -1,
          jsonMode: false
        }),
      });

      const textData = await response.text();
      const cleanedTranslation = textData
        .replace(/^[^a-zA-ZğüşıöçĞÜŞİÖÇ]+/g, '')
        .replace(/["']/g, '')
        .replace(/^\d+\.\s*/gm, '')
        .split('\n')
        .filter(line => line.trim())
        .join(', ');

      setTranslation(cleanedTranslation);
    } catch (error) {
      console.error('Translation error:', error);
      setTranslation(locale === 'tr' ? 'Çeviri alınamadı' : 'Translation failed');
    } finally {
      setLoading(false);
    }
  }, [locale]);

  const cleanArabicPunctuation = (text) => {
    return text.trim();
  };

  const fetchTranslation = useCallback(async (text) => {
    setLoading(true);
    setTranslationSource('google');
    try {
      const cleanedText = cleanArabicPunctuation(text);
      const translateResponse = await translate(cleanedText, { 
        to: locale === 'tr' ? 'tr' : 'en' 
      });
      setTranslation(translateResponse[0]);
    } catch (error) {
      console.error('Error fetching translation:', error);
      setTranslation(locale === 'tr' ? 'Çeviri alınamadı' : 'Translation failed');
    } finally {
      setLoading(false);
    }
  }, [locale]);

  const measureElement = useCallback((ref, callback) => {
    if (measuringInProgress.current) return;
    measuringInProgress.current = true;

    const measureAndSetRect = () => {
      ref.current.measure((x, y, width, height, pageX, pageY) => {
        scrollViewRef.current.measure((sx, sy, swidth, sheight, spageX, spageY) => {
          const scrollOffset = scrollViewRef.current._scrollMetrics?.offset || 0;
          const actualY = pageY - spageY + scrollOffset;
          
          const newRect = new Rect(
            pageX,
            actualY,
            width,
            height
          );
          setRect(newRect);
          measuringInProgress.current = false;
          if (callback) callback();
        });
      });
    };

    requestAnimationFrame(measureAndSetRect);
  }, []);

  const handleTextPress = useCallback((text, ref, isWord = true) => {
    if (selectedText === text && popoverVisible) {
      setPopoverVisible(false);
      setSelectedText('');
      setTranslationSource(null);
      return;
    }

    setSelectedText(text);
    
    measureElement(ref, () => {
      setPopoverVisible(true);
      if (isWord) {
        getTranslation(text, isWord);
      } else {
        fetchTranslation(text);
      }
    });
  }, [selectedText, popoverVisible, getTranslation, fetchTranslation, measureElement]);

  const splitIntoSentences = (text) => {
    // Arabic-specific sentence splitting
    return text.match(/[^.!?؟،,]+[.!?؟،,]+/g) || [];
  };

  const cleanDescription = item.content.replace(/<[^>]+>/g, '');
  const sentences = splitIntoSentences(cleanDescription);

  const titleRef = useRef(null);

  const renderContent = useCallback(() => {
    let currentSentence = [];
    
    return (
      <View style={styles.textWrapper}>
        {sentences.map((sentence, sentenceIndex) => {
          const words = sentence.trim().split(' ');
          const sentenceRef = useRef(null);
          currentSentence = [];

          return (
            <View key={sentenceIndex} style={styles.sentenceContainer}>
              <View style={styles.sentenceContent}>
                {words.map((word, wordIndex) => {
                  const wordRef = useRef(null);
                  currentSentence.push(word);
                  
                  const isLastWord = wordIndex === words.length - 1;
                  return (
                    <TouchableOpacity
                      key={`${sentenceIndex}-${wordIndex}`}
                      ref={wordRef}
                      onPress={() => handleTextPress(word, wordRef, true)}
                      style={styles.wordContainer}
                    >
                      <Text style={[
                        styles.word, 
                        { 
                          color: theme.textColor,
                          fontFamily: arabicFont,
                          textAlign: 'right',
                        }
                      ]}>
                        {word}{!isLastWord ? ' ' : ''}
                      </Text>
                    </TouchableOpacity>
                  );
                })}
                <TouchableOpacity 
                  ref={sentenceRef}
                  onPress={() => handleTextPress(sentence.trim(), sentenceRef, false)}
                  style={[styles.translateButtonImage, { alignSelf: 'center' }]}
                >
                  <Image
                    source={translateIcon}
                    style={styles.translateIcon}
                  />
                </TouchableOpacity>
              </View>
            </View>
          );
        })}
      </View>
    );
  }, [sentences, handleTextPress, theme.textColor, arabicFont]);

  const handlePopoverClose = useCallback(() => {
    setPopoverVisible(false);
    setSelectedText('');
    setTranslationSource(null);
  }, []);

  return (
    <View style={styles.container}>
      <StatusBar translucent backgroundColor="transparent" />
      <ScrollView
        ref={scrollViewRef}
        style={[styles.scrollView, { backgroundColor: theme.backgroundColor }]}
        scrollEventThrottle={16}
        onScroll={() => {
          if (popoverVisible) {
            handlePopoverClose();
          }
        }}
      >
        {item.thumbnail && (
          <View style={styles.coverContainer}>
            <Image
              source={{ uri: item.thumbnail }}
              style={styles.coverImage}
              resizeMode="cover"
            />
            <LinearGradient
              colors={['transparent', theme.backgroundColor]}
              style={styles.gradient}
              start={{ x: 0, y: 0 }}
              end={{ x: 0, y: 1 }}
            />
          </View>
        )}

        <View style={[
          styles.contentContainer, 
          { 
            marginTop: item.thumbnail ? -60 : 0,
            backgroundColor: theme.backgroundColor 
          }
        ]}>
          <TouchableOpacity
            ref={titleRef}
            onPress={() => handleTextPress(item.title, titleRef, false)}
          >
            <CustomTextB 
              style={[
                styles.title, 
                { 
                  color: theme.textColor,
                  fontFamily: arabicFontBold,
                  textAlign: 'right',
                }
              ]}
            >
              {item.title}
            </CustomTextB>
            {item.source && (
              <Text 
                style={[
                  styles.sourceLabel, 
                  { 
                    color: theme.textColor,
                    fontFamily: arabicFont,
                    textAlign: 'right',
                    paddingRight: 4,
                  }
                ]}
              >
                {locale === 'tr' ? 'المصدر: ' : 'Source: '}{item.source}
              </Text>
            )}
          </TouchableOpacity>

          <View style={[styles.divider, { backgroundColor: theme.borderColor }]} />

          <View style={styles.textContainer}>
            {renderContent()}
          </View>

          <Popover
            isVisible={popoverVisible}
            onRequestClose={handlePopoverClose}
            from={rect}
            popoverStyle={[
              styles.popover,
              { backgroundColor: theme.backgroundColor }
            ]}
            placement="top"
            arrowSize={{ width: 16, height: 8 }}
            arrowStyle={{ backgroundColor: theme.backgroundColor }}
            backgroundStyle={styles.popoverBackground}
            offset={-60}
            animationConfig={{
              duration: 0,
              delay: 0,
              useNativeDriver: true
            }}
          >
            <View 
              style={styles.popoverContent}
              onLayout={(event) => {
                const { height } = event.nativeEvent.layout;
                if (height !== popoverContentHeight.current) {
                  popoverContentHeight.current = height;
                }
              }}
            >
              <View style={styles.popoverContentWrapper}>
                {loading ? (
                  <ActivityIndicator color={theme.primaryColor} size="small" />
                ) : (
                  <>
                    <CustomTextR 
                      style={[
                        styles.tooltipText, 
                        { 
                          color: theme.textColor,
                          fontFamily: arabicFont 
                        }
                      ]}
                    >
                      {translation || (locale === 'tr' ? 'Çeviriliyor...' : 'Translating...')}
                    </CustomTextR>
                    {translationSource && (
                      <View style={styles.translationSourceContainer}>
                        <Image
                          source={translationSource === 'google' ? GOOGLE_TRANSLATE_LOGO : CHATGPT_LOGO}
                          style={styles.translationSourceLogo}
                        />
                        <CustomTextR 
                          style={[
                            styles.translationSourceText, 
                            { 
                              color: theme.textColor,
                              fontFamily: arabicFont 
                            }
                          ]}
                        >
                          {translationSource === 'google' ? t('googleTranslateWarning') : t('chatgpt')}
                        </CustomTextR>
                      </View>
                    )}
                  </>
                )}
              </View>
            </View>
          </Popover>
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  coverContainer: {
    height: SCREEN_HEIGHT * 0.5,
    width: SCREEN_WIDTH,
    position: 'relative',
  },
  coverImage: {
    width: '100%',
    height: '100%',
  },
  gradient: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: 200,
  },
  contentContainer: {
    padding: 20,
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    marginTop: -60,
  },
  title: {
    fontSize: 32,
    marginBottom: 10,
    lineHeight: 44,
    textShadowColor: "rgba(0, 0, 0, 0.1)",
    textShadowOffset: { width: 0, height: 2 },
    textShadowRadius: 4,
  },
  sourceLabel: {
    fontSize: 14,
    marginTop: 8,
    opacity: 0.8,
  },
  divider: {
    height: 1,
    marginVertical: 20,
    width: '100%',
  },
  textContainer: {
    marginTop: 16,
  },
  textWrapper: {
    flexDirection: 'column',
  },
  sentenceContainer: {
    marginBottom: 8,
  },
  sentenceContent: {
    flexDirection: 'row-reverse',
    flexWrap: 'wrap',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  wordContainer: {
    flexDirection: 'row',
  },
  word: {
    fontSize: 20,
    lineHeight: 36,
    letterSpacing: 0.5,
  },
  translateButtonImage: {
    padding: 3,
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 5,
  },
  translateIcon: {
    width: 24,
    height: 24,
    resizeMode: 'contain',
  },
  popover: {
    borderRadius: 12,
    padding: 0,
    width: SCREEN_WIDTH * 0.8,
    maxWidth: 300,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.25,
    shadowRadius: 8,
    elevation: 8,
  },
  popoverContent: {
    minHeight: 60,
  },
  popoverContentWrapper: {
    padding: 16,
    alignItems: 'center',
    justifyContent: 'center',
    minHeight: 60,
  },
  tooltipText: {
    fontSize: 16,
    textAlign: 'center',
    lineHeight: 24,
  },
  popoverBackground: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  translationSourceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  translationSourceLogo: {
    width: 20,
    height: 20,
    marginRight: 8,
    resizeMode: 'contain',
  },
  translationSourceText: {
    fontSize: 14,
  },
});

export default RSSReadScreen; bu koduma göndereceğim güncellemeleri uygula:

güncellemeler:
// ... (previous imports and initial code remains the same until renderContent)

  const renderContent = useCallback(() => {
    return (
      <View style={styles.textWrapper}>
        <View style={styles.textFlow}>
          {sentences.map((sentence, sentenceIndex) => {
            const words = sentence.trim().split(' ');
            const sentenceRef = useRef(null);

            return (
              <View key={sentenceIndex} style={styles.inlineSentence}>
                <TouchableOpacity 
                  ref={sentenceRef}
                  onPress={() => handleTextPress(sentence.trim(), sentenceRef, false)}
                  style={styles.translateButtonImage}
                >
                  <Image
                    source={translateIcon}
                    style={styles.translateIcon}
                  />
                </TouchableOpacity>
                {words.map((word, wordIndex) => {
                  const wordRef = useRef(null);
                  return (
                    <TouchableOpacity
                      key={`${sentenceIndex}-${wordIndex}`}
                      ref={wordRef}
                      onPress={() => handleTextPress(word, wordRef, true)}
                      style={styles.wordContainer}
                    >
                      <Text style={[
                        styles.word, 
                        { 
                          color: theme.textColor,
                          fontFamily: arabicFont,
                        }
                      ]}>
                        {word}{wordIndex < words.length - 1 ? ' ' : ''}
                      </Text>
                    </TouchableOpacity>
                  );
                })}
              </View>
            );
          })}
        </View>
      </View>
    );
  }, [sentences, handleTextPress, theme.textColor, arabicFont]);

  // ... (rest of the component code remains the same until styles)

const styles = StyleSheet.create({
  // ... (previous styles remain the same)
  
  textWrapper: {
    flex: 1,
  },
  textFlow: {
    flexDirection: 'row-reverse',
    flexWrap: 'wrap',
    alignItems: 'flex-start',
    justifyContent: 'flex-end',
  },
  inlineSentence: {
    flexDirection: 'row-reverse',
    flexWrap: 'wrap',
    alignItems: 'center',
  },
  wordContainer: {
    flexDirection: 'row-reverse',
  },
  word: {
    fontSize: 20,
    lineHeight: 36,
    letterSpacing: 0.5,
    textAlign: 'right',
  },
  translateButtonImage: {
    padding: 3,
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 5,
  },
  translateIcon: {
    width: 24,
    height: 24,
    resizeMode: 'contain',
  },

  // ... (rest of the styles remain the same)
});

// ... (rest of the file remains the same)