import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Switch, ScrollView, Image, Animated, Linking, Alert, Platform, TextInput, Modal, Vibration, Share } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';
import { 
  User, 
  Moon, 
  Sun, 
  LogOut, 
  ChevronRight, 
  Bell, 
  HelpCircle, 
  Shield, 
  MessageSquare, 
  Share2, 
  Settings, 
  CreditCard,
  Globe,
  DollarSign,
  Mail,
  Lock,
  UserPlus,
  Check,
  AlertCircle,
  Cloud
} from 'lucide-react-native';
import useTradeStore from '@/store/useTradeStore';
import { useTheme } from '@/context/ThemeContext';
import CountrySelector from '@/components/CountrySelector';
import MessageModal from '@/components/MessageModal';
import { CONFIG } from '@/constants/config';
import { APP_LINKS } from '@/constants/appLinks';
import { useToast } from '@/context/ToastContext';
import AsyncStorage from '@react-native-async-storage/async-storage';
import AuthModal from '@/components/AuthModal';
import { useAuth } from '@/hooks/useAuth';
import SyncDataButton from '@/components/SyncDataButton';
import { Stack } from 'expo-router';

export default function ProfileScreen() {
  const router = useRouter();
  const { 
    userProfile, 
    updateUserProfile, 
    messages, 
    markMessagesAsRead,
    newMessages,
    userCountry,
    setUserCountry,
    isUserFromNigeria,
    darkMode,
    toggleDarkMode,
    setDarkMode
  } = useTradeStore();
  
  const { theme, colors, toggleTheme, setTheme } = useTheme();
  const { showToast } = useToast();
  const { user, logout, syncUserData } = useAuth();
  
  // State
  const [showCountrySelector, setShowCountrySelector] = useState(false);
  const [showMessageModal, setShowMessageModal] = useState(false);
  const [isDarkMode, setIsDarkMode] = useState(darkMode);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authMode, setAuthMode] = useState<'login' | 'register'>('login');
  const [switchAnimating, setSwitchAnimating] = useState(false);
  const [isSharing, setIsSharing] = useState(false);
  const [isScrolling, setIsScrolling] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);
  
  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;
  const switchAnim = useRef(new Animated.Value(1)).current;
  const switchThumbAnim = useRef(new Animated.Value(isDarkMode ? 1 : 0)).current;
  const shareButtonAnim = useRef(new Animated.Value(1)).current;
  
  // Animate on mount
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 800,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);
  
  // Keep local state in sync with store
  useEffect(() => {
    setIsDarkMode(darkMode);
    
    // Animate switch thumb position
    Animated.spring(switchThumbAnim, {
      toValue: darkMode ? 1 : 0,
      friction: 8,
      tension: 50,
      useNativeDriver: true,
    }).start();
  }, [darkMode]);
  
  // Interpolate transform for switch thumb
  const thumbTranslateX = switchThumbAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [2, 22], // Adjust based on your design
  });
  
  const handleLogout = () => {
    Alert.alert(
      "Logout",
      "Are you sure you want to logout?",
      [
        {
          text: "Cancel",
          style: "cancel"
        },
        { 
          text: "Logout", 
          onPress: async () => {
            // Provide haptic feedback on native platforms
            if (Platform.OS !== 'web') {
              try {
                Vibration.vibrate(20);
              } catch (error) {
                console.error("Vibration error:", error);
              }
            }
            
            try {
              await logout();
            } catch (error) {
              console.error("Error logging out:", error);
              showToast("Failed to logout. Please try again.", "error");
            }
          },
          style: "destructive"
        }
      ]
    );
  };
  
  const handleOpenMessages = () => {
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(10);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    setShowMessageModal(true);
    markMessagesAsRead();
  };
  
  const handleShare = async () => {
    try {
      // Prevent multiple share attempts
      if (isSharing) return;
      setIsSharing(true);
      
      // Provide haptic feedback on native platforms
      if (Platform.OS !== 'web') {
        try {
          Vibration.vibrate(10);
        } catch (error) {
          console.error("Vibration error:", error);
        }
      }
      
      // Animate the share button
      Animated.sequence([
        Animated.timing(shareButtonAnim, {
          toValue: 0.9,
          duration: 100,
          useNativeDriver: true,
        }),
        Animated.timing(shareButtonAnim, {
          toValue: 1.1,
          duration: 100,
          useNativeDriver: true,
        }),
        Animated.timing(shareButtonAnim, {
          toValue: 1,
          duration: 100,
          useNativeDriver: true,
        }),
      ]).start();
      
      // Get the appropriate app store link based on platform
      let appLink = APP_LINKS.website; // Default to website
      
      if (Platform.OS === 'ios') {
        appLink = APP_LINKS.appStore;
      } else if (Platform.OS === 'android') {
        appLink = APP_LINKS.googlePlay;
      }
      
      // Create share message with appropriate link
      const shareMessage = `${APP_LINKS.shareMessage}

Download here: ${appLink}`;
      
      if (Platform.OS === 'web') {
        // Web implementation - use clipboard and show alert
        try {
          // Use the Web Share API if available
          if (navigator.share) {
            await navigator.share({
              title: APP_LINKS.shareTitle,
              text: APP_LINKS.shareMessage,
              url: appLink,
            });
            showToast("Thank you for sharing BATZ Trade!", "success");
          } else {
            // Fallback for browsers that don't support Web Share API
            Alert.alert(
              "Share BATZ Trade",
              "Copy this link to share with friends and family:",
              [
                {
                  text: "Copy Link",
                  onPress: async () => {
                    try {
                      await navigator.clipboard.writeText(appLink);
                      showToast("Link copied to clipboard!", "success");
                    } catch (err) {
                      showToast("Failed to copy link. Please try again.", "error");
                    }
                  }
                },
                {
                  text: "Cancel",
                  style: "cancel"
                }
              ]
            );
          }
        } catch (error) {
          console.error("Web share error:", error);
          Alert.alert(
            "Share BATZ Trade",
            `Share this link with your friends and family: ${appLink}`,
            [
              {
                text: "OK",
                onPress: () => showToast("Thank you for sharing BATZ Trade!", "success")
              }
            ]
          );
        }
      } else {
        // Native implementation - use Share API
        try {
          const result = await Share.share({
            message: shareMessage,
            title: APP_LINKS.shareTitle,
            url: appLink, // iOS only
          });
          
          if (result.action === Share.sharedAction) {
            if (result.activityType) {
              // Shared with activity type of result.activityType
              showToast(`Shared via ${result.activityType}`, "success");
            } else {
              // Shared
              showToast("Thank you for sharing BATZ Trade!", "success");
            }
          } else if (result.action === Share.dismissedAction) {
            // Dismissed
            showToast("Share cancelled", "info");
          }
        } catch (error) {
          console.error("Error sharing:", error);
          Alert.alert("Error", "Failed to share. Please try again.");
        }
      }
    } catch (error) {
      console.error("Error in handleShare:", error);
      Alert.alert("Error", "Failed to share. Please try again.");
    } finally {
      setIsSharing(false);
    }
  };
  
  const handleToggleDarkMode = async () => {
    if (switchAnimating) return;
    
    setSwitchAnimating(true);
    
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(10);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    // Animate the switch
    Animated.sequence([
      Animated.timing(switchAnim, {
        toValue: 0.9,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.timing(switchAnim, {
        toValue: 1.1,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.timing(switchAnim, {
        toValue: 1,
        duration: 100,
        useNativeDriver: true,
      }),
    ]).start(async () => {
      try {
        // Update both the local state and the store
        const newMode = !isDarkMode;
        setIsDarkMode(newMode);
        
        // Save to AsyncStorage directly
        await AsyncStorage.setItem('app-theme', newMode ? 'dark' : 'light');
        
        // Update store and theme context
        setDarkMode(newMode);
        setTheme(newMode ? 'dark' : 'light');
        
        // Show toast notification
        showToast(`Dark mode ${newMode ? 'enabled' : 'disabled'}`, "info");
      } catch (error) {
        console.error("Error toggling dark mode:", error);
        showToast("Failed to change theme", "error");
      } finally {
        setSwitchAnimating(false);
      }
    });
  };
  
  const handleCountryChange = (country: string) => {
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(10);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    // Set the country in the store
    setUserCountry(country);
    setShowCountrySelector(false);
    
    // Show toast notification
    const currencySymbol = country === 'NG' ? 'NGN' : 'USDT';
    showToast(`Currency set to ${currencySymbol}`, "success");
  };
  
  const handleOpenDeposit = () => {
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(10);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    router.push({
      pathname: '/',
      params: { openDepositModal: 'true'
      }
    });
  };
  
  const handleSyncData = async () => {
    if (isSyncing || !user) return;
    
    try {
      setIsSyncing(true);
      
      // Provide haptic feedback on native platforms
      if (Platform.OS !== 'web') {
        try {
          Vibration.vibrate(10);
        } catch (error) {
          console.error("Vibration error:", error);
        }
      }
      
      await syncUserData();
      showToast("Your data has been synced to the cloud", "success");
    } catch (error) {
      console.error("Error syncing data:", error);
      showToast("Failed to sync data. Please try again.", "error");
    } finally {
      setIsSyncing(false);
    }
  };
  
  // Scroll event handlers
  const handleScrollBegin = useCallback(() => {
    setIsScrolling(true);
  }, []);
  
  const handleScrollEnd = useCallback(() => {
    setIsScrolling(false);
  }, []);
  
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['top']}>
      {/* Add Stack.Screen to set the header title */}
      <Stack.Screen options={{ headerTitle: "Profile", headerShown: true }} />
      
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
          style={styles.backgroundGradient}
        />
      )}
      
      <Animated.View 
        style={[
          styles.content,
          { 
            opacity: fadeAnim,
            transform: [{ translateY: slideAnim }]
          }
        ]}
      >
        <ScrollView 
          style={styles.scrollContent}
          contentContainerStyle={styles.scrollContentContainer}
          showsVerticalScrollIndicator={false}
          scrollEventThrottle={16}
          onScrollBeginDrag={handleScrollBegin}
          onScrollEndDrag={handleScrollEnd}
          onMomentumScrollBegin={handleScrollBegin}
          onMomentumScrollEnd={handleScrollEnd}
          decelerationRate={Platform.OS === 'ios' ? 'normal' : 0.985}
          overScrollMode="never"
          bounces={false}
          bouncesZoom={false}
          alwaysBounceVertical={false}
          alwaysBounceHorizontal={false}
          removeClippedSubviews={Platform.OS !== 'web'}
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="on-drag"
        >
          <View 
            style={[styles.profileCard, { backgroundColor: colors.backgroundSecondary }]}
          >
            <LinearGradient
              colors={theme === 'dark' 
                ? ['rgba(30, 39, 46, 0.8)', 'rgba(30, 39, 46, 0.5)'] 
                : ['rgba(41, 171, 226, 0.1)', 'rgba(41, 171, 226, 0.02)']}
              style={styles.cardGradient}
            />
            
            <View style={styles.profileInfo}>
              <View style={[styles.avatarContainer, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
                <User size={24} color={colors.primary} />
              </View>
              <View style={styles.profileDetails}>
                <Text style={[styles.profileName, { color: colors.text }]}>{userProfile.name}</Text>
                <Text style={[styles.profileId, { color: colors.textSecondary }]}>ID: {userProfile.id}</Text>
                {userProfile.email && (
                  <Text style={[styles.profileEmail, { color: colors.textSecondary }]}>{userProfile.email}</Text>
                )}
              </View>
            </View>
            
            {userProfile.isLoggedIn ? (
              <View style={styles.actionButtons}>
                <SyncDataButton />
                <TouchableOpacity 
                  style={[styles.logoutButton, { backgroundColor: theme === 'dark' ? 'rgba(231, 76, 60, 0.1)' : 'rgba(231, 76, 60, 0.05)' }]}
                  onPress={handleLogout}
                  activeOpacity={0.7}
                >
                  <LogOut size={16} color={colors.error} />
                  <Text style={[styles.logoutText, { color: colors.error }]}>Logout</Text>
                </TouchableOpacity>
              </View>
            ) : (
              <View style={styles.authButtons}>
                <TouchableOpacity 
                  style={[styles.loginButton, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}
                  onPress={() => {
                    setAuthMode('login');
                    setShowAuthModal(true);
                  }}
                  activeOpacity={0.7}
                >
                  <User size={16} color={colors.primary} />
                  <Text style={[styles.loginText, { color: colors.primary }]}>Login</Text>
                </TouchableOpacity>
                
                <TouchableOpacity 
                  style={[styles.registerButton, { backgroundColor: theme === 'dark' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(46, 204, 113, 0.05)' }]}
                  onPress={() => {
                    setAuthMode('register');
                    setShowAuthModal(true);
                  }}
                  activeOpacity={0.7}
                >
                  <UserPlus size={16} color={colors.success} />
                  <Text style={[styles.registerButtonText, { color: colors.success }]}>Register</Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
          
          <View style={styles.sectionTitle}>
            <Text style={[styles.sectionTitleText, { color: colors.textSecondary }]}>Account</Text>
          </View>
          
          <View style={[styles.menuCard, { backgroundColor: colors.backgroundSecondary }]}>
            {theme === 'dark' && (
              <LinearGradient
                colors={['rgba(30, 39, 46, 0.8)', 'rgba(30, 39, 46, 0.5)']}
                style={styles.cardGradient}
              />
            )}
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={handleOpenDeposit}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(243, 156, 18, 0.1)' : 'rgba(243, 156, 18, 0.05)' }]}>
                  <CreditCard size={18} color={colors.accent} />
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Deposit Methods</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    Add funds to your account
                  </Text>
                </View>
              </View>
              <ChevronRight size={18} color={colors.textSecondary} />
            </TouchableOpacity>
            
            <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={() => setShowCountrySelector(true)}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(46, 204, 113, 0.05)' }]}>
                  <Globe size={18} color={colors.success} />
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Region</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    {userCountry === 'NG' ? 'Nigeria (NGN)' : 'International (USDT)'}
                  </Text>
                </View>
              </View>
              <ChevronRight size={18} color={colors.textSecondary} />
            </TouchableOpacity>
            
            <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={() => router.push('/withdraw')}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
                  <DollarSign size={18} color={colors.primary} />
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Withdraw Funds</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    Cash out your earnings
                  </Text>
                </View>
              </View>
              <ChevronRight size={18} color={colors.textSecondary} />
            </TouchableOpacity>
          </View>
          
          <View style={styles.sectionTitle}>
            <Text style={[styles.sectionTitleText, { color: colors.textSecondary }]}>Preferences</Text>
          </View>
          
          <View style={[styles.menuCard, { backgroundColor: colors.backgroundSecondary }]}>
            {theme === 'dark' && (
              <LinearGradient
                colors={['rgba(30, 39, 46, 0.8)', 'rgba(30, 39, 46, 0.5)']}
                style={styles.cardGradient}
              />
            )}
            
            <View style={styles.menuItem}>
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(155, 89, 182, 0.1)' : 'rgba(155, 89, 182, 0.05)' }]}>
                  {isDarkMode ? 
                    <Moon size={18} color="#9B59B6" /> : 
                    <Sun size={18} color="#F39C12" />
                  }
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Dark Mode</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    {isDarkMode ? "ON" : "OFF"}
                  </Text>
                </View>
              </View>
              <Animated.View style={{ transform: [{ scale: switchAnim }] }}>
                <TouchableOpacity 
                  onPress={handleToggleDarkMode}
                  disabled={switchAnimating}
                  style={styles.customSwitchContainer}
                  activeOpacity={0.8}
                >
                  <Animated.View 
                    style={[
                      styles.customSwitchTrack,
                      { 
                        backgroundColor: isDarkMode 
                          ? 'rgba(41, 171, 226, 0.4)' 
                          : theme === 'dark' ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.2)'
                      }
                    ]}
                  >
                    <Animated.View 
                      style={[
                        styles.customSwitchThumb,
                        { 
                          backgroundColor: isDarkMode ? colors.primary : '#f4f3f4',
                          transform: [{ translateX: thumbTranslateX }]
                        }
                      ]}
                    />
                  </Animated.View>
                </TouchableOpacity>
              </Animated.View>
            </View>
            
            <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={handleOpenMessages}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
                  <MessageSquare size={18} color={colors.primary} />
                  {newMessages && (
                    <View style={styles.notificationDot} />
                  )}
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Messages</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    {newMessages ? "New messages available" : "No new messages"}
                  </Text>
                </View>
              </View>
              <View style={styles.menuItemRight}>
                {newMessages && (
                  <View style={styles.badgeContainer}>
                    <Text style={styles.badgeText}>{messages.filter(m => !m.read).length}</Text>
                  </View>
                )}
                <ChevronRight size={18} color={colors.textSecondary} />
              </View>
            </TouchableOpacity>
            
            <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
            
            <Animated.View style={{ transform: [{ scale: shareButtonAnim }] }}>
              <TouchableOpacity 
                style={styles.menuItem}
                onPress={handleShare}
                disabled={isSharing}
                activeOpacity={0.7}
              >
                <View style={styles.menuItemLeft}>
                  <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(46, 204, 113, 0.05)' }]}>
                    <Share2 size={18} color={colors.success} />
                  </View>
                  <View>
                    <Text style={[styles.menuItemText, { color: colors.text }]}>
                      {isSharing ? 'Sharing...' : 'Share App'}
                    </Text>
                    <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                      Tell friends about BATZ Trade
                    </Text>
                  </View>
                </View>
                <ChevronRight size={18} color={colors.textSecondary} />
              </TouchableOpacity>
            </Animated.View>
          </View>
          
          <View style={styles.sectionTitle}>
            <Text style={[styles.sectionTitleText, { color: colors.textSecondary }]}>Support</Text>
          </View>
          
          <View style={[styles.menuCard, { backgroundColor: colors.backgroundSecondary }]}>
            {theme === 'dark' && (
              <LinearGradient
                colors={['rgba(30, 39, 46, 0.8)', 'rgba(30, 39, 46, 0.5)']}
                style={styles.cardGradient}
              />
            )}
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={() => router.push('/help-support')}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
                  <HelpCircle size={18} color={colors.primary} />
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Help & Support</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    Get assistance with the app
                  </Text>
                </View>
              </View>
              <ChevronRight size={18} color={colors.textSecondary} />
            </TouchableOpacity>
            
            <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
            
            <TouchableOpacity 
              style={styles.menuItem}
              onPress={() => router.push('/privacy-policy')}
              activeOpacity={0.7}
            >
              <View style={styles.menuItemLeft}>
                <View style={[styles.menuItemIcon, { backgroundColor: theme === 'dark' ? 'rgba(231, 76, 60, 0.1)' : 'rgba(231, 76, 60, 0.05)' }]}>
                  <Shield size={18} color={colors.error} />
                </View>
                <View>
                  <Text style={[styles.menuItemText, { color: colors.text }]}>Privacy Policy</Text>
                  <Text style={[styles.menuItemSubtext, { color: colors.textSecondary }]}>
                    How we protect your data
                  </Text>
                </View>
              </View>
              <ChevronRight size={18} color={colors.textSecondary} />
            </TouchableOpacity>
          </View>
          
          <View style={styles.appInfo}>
            <Image 
              source={{ uri: 'https://cdn.prod.website-files.com/66b7dcae754fe5eef2139e69/67d2bd08bfc05787cd4dc601_THE%20BATZ%20Trade%20logo.png' }}
              style={styles.appLogo}
              resizeMode="contain"
            />
            <Text style={[styles.appVersion, { color: colors.textSecondary }]}>Version {CONFIG.appVersion}</Text>
            <Text style={[styles.copyright, { color: colors.textSecondary }]}>© 2023 BATZ Trade. All rights reserved.</Text>
          </View>
        </ScrollView>
      </Animated.View>
      
      {/* Country Selector Modal */}
      <CountrySelector 
        visible={showCountrySelector}
        onClose={() => setShowCountrySelector(false)}
        onSelect={handleCountryChange}
        selectedCountry={userCountry}
      />
      
      {/* Messages Modal */}
      <MessageModal 
        visible={showMessageModal}
        onClose={() => setShowMessageModal(false)}
        messages={messages}
      />
      
      {/* Auth Modal */}
      <AuthModal
        visible={showAuthModal}
        onClose={() => setShowAuthModal(false)}
        initialMode={authMode}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  cardGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  content: {
    flex: 1,
  },
  scrollContent: {
    flex: 1,
  },
  scrollContentContainer: {
    paddingTop: 16,
    paddingBottom: 24,
  },
  profileCard: {
    marginHorizontal: 16,
    padding: 16,
    borderRadius: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    position: 'relative',
    overflow: 'hidden',
  },
  profileInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  avatarContainer: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
  },
  profileDetails: {
    marginLeft: 12,
    flex: 1,
  },
  profileName: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 2,
  },
  profileId: {
    fontSize: 12,
  },
  profileEmail: {
    fontSize: 12,
    marginTop: 2,
  },
  actionButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  authButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  loginButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    flex: 1,
    marginRight: 8,
    justifyContent: 'center',
  },
  loginText: {
    marginLeft: 6,
    fontSize: 14,
    fontWeight: '500',
  },
  registerButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    flex: 1,
    marginLeft: 8,
    justifyContent: 'center',
  },
  registerButtonText: {
    marginLeft: 6,
    fontSize: 14,
    fontWeight: '500',
  },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 8,
  },
  logoutText: {
    marginLeft: 6,
    fontSize: 14,
    fontWeight: '500',
  },
  sectionTitle: {
    marginTop: 24,
    marginBottom: 8,
    paddingHorizontal: 16,
  },
  sectionTitleText: {
    fontSize: 14,
    fontWeight: '500',
    textTransform: 'uppercase',
  },
  menuCard: {
    marginHorizontal: 16,
    borderRadius: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    overflow: 'hidden',
    position: 'relative',
  },
  menuItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  menuItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  menuItemIcon: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
    position: 'relative',
  },
  menuItemText: {
    fontSize: 15,
    fontWeight: '500',
  },
  menuItemSubtext: {
    fontSize: 12,
    marginTop: 2,
  },
  menuItemRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  divider: {
    height: 1,
    marginHorizontal: 16,
  },
  notificationDot: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: '#E74C3C',
  },
  badgeContainer: {
    backgroundColor: '#E74C3C',
    borderRadius: 10,
    paddingHorizontal: 6,
    paddingVertical: 2,
    marginRight: 8,
  },
  badgeText: {
    color: '#FFFFFF',
    fontSize: 10,
    fontWeight: 'bold',
  },
  appInfo: {
    alignItems: 'center',
    marginTop: 32,
    marginBottom: 16,
  },
  appLogo: {
    width: 100,
    height: 40,
    marginBottom: 8,
  },
  appVersion: {
    fontSize: 12,
    marginBottom: 4,
  },
  copyright: {
    fontSize: 10,
  },
  
  // Custom Switch Styles
  customSwitchContainer: {
    padding: 4,
  },
  customSwitchTrack: {
    width: 44,
    height: 24,
    borderRadius: 12,
    padding: 2,
  },
  customSwitchThumb: {
    width: 20,
    height: 20,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 1,
    elevation: 2,
  },
});