this is an expo project
 LOG  Token loaded from SecureStore: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NmZmNGMzZDdhOTliZGYyZjdhYzYwMjQiLCJpYXQiOjE3MjgwMDkwNTMsImV4cCI6MTcyODAxMjY1M30.mnHhtg92Sud9bQFKiUn6-RTx4Z_dSV305bl5r0hm6sU
 LOG  Failed to load token: [TypeError: 0, _jwtDecode.default is not a function (it is undefined)]

// screens/ProfileScreen.js

import React, { useContext } from 'react';
import { View, StyleSheet, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { Title, Caption, Text, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { AuthContext } from '../context/AuthContext';
import { useTheme } from 'react-native-paper';

/**
 * ProfileScreen Component
 * Displays the authenticated user's profile information.
 */
const ProfileScreen = ({ navigation }) => {
  const { user, signOut, loading } = useContext(AuthContext);
  const theme = useTheme(); // Access the current theme

  /**
   * Handler for the logout button
   */
  const handleLogout = () => {
    Alert.alert(
      'Logout',
      'Are you sure you want to logout?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Logout',
          style: 'destructive',
          onPress: () => signOut(),
        },
      ],
      { cancelable: true }
    );
  };

  /**
   * If the app is still loading user data, show a loading indicator
   */
  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={theme.colors.primary} />
      </View>
    );
  }

  /**
   * If no user is logged in, prompt the user to log in
   */
  if (!user) {
    return (
      <View style={styles.container}>
        <Text>No user data available. Please log in.</Text>
        <Button mode="contained" onPress={() => navigation.navigate('Login')} style={styles.loginButton}>
          Go to Login
        </Button>
      </View>
    );
  }

  /**
   * Render the user's profile information
   */
  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* User Information Section */}
      <View style={styles.userInfoSection}>
        <Title style={[styles.title, { color: theme.colors.text }]}>{user.name}</Title>
        <Caption style={[styles.caption, { color: theme.colors.text }]}>{user.email}</Caption>
      </View>

      {/* Logout Button */}
      <View style={styles.logoutSection}>
        <Button
          mode="contained"
          icon="logout"
          onPress={handleLogout}
          style={styles.logoutButton}
          contentStyle={styles.buttonContent}
          accessibilityLabel="Logout"
          accessibilityHint="Logs you out of the application"
        >
          Logout
        </Button>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  userInfoSection: {
    paddingHorizontal: 20,
    paddingVertical: 40,
    alignItems: 'center', // Center the user info
    backgroundColor: 'transparent',
  },
  title: {
    fontSize: 26,
    fontWeight: 'bold',
  },
  caption: {
    fontSize: 16,
    lineHeight: 16,
    marginTop: 5,
  },
  logoutSection: {
    paddingHorizontal: 20,
    marginTop: 30,
    alignItems: 'center', // Center the logout button
  },
  logoutButton: {
    width: '100%', // Make the button stretch across the container
    borderRadius: 5,
    backgroundColor: undefined, // Let the theme handle the color
  },
  buttonContent: {
    height: 50, // Ensures consistent button height
    justifyContent: 'center',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loginButton: {
    marginTop: 20,
    borderRadius: 25,
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
});

export default ProfileScreen;

// context/AuthContext.js

import React, { createContext, useState, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';
import { Alert } from 'react-native';
import jwtDecode from 'jwt-decode'; // Correctly imported
import axios from 'axios';

export const AuthContext = createContext();

/**
 * AuthProvider Component
 * Provides authentication context to the application.
 */
export const AuthProvider = ({ children }) => {
  const [authToken, setAuthToken] = useState(null);
  const [user, setUser] = useState(null); // Manage user object
  const [loading, setLoading] = useState(true); // Loading state to manage asynchronous operations

  const SIGNIN_KEY = 'authToken';

  /**
   * Function to handle user sign-in
   * @param {String} token - JWT token received from the backend
   */
  const signIn = async (token) => {
    try {
      if (token && token.split('.').length === 3) { // Basic JWT structure validation
        setAuthToken(token);
        await SecureStore.setItemAsync(SIGNIN_KEY, token);
        console.log('Token stored successfully:', token); // Debugging

        // Decode the token to extract user information
        const decoded = jwtDecode(token);
        setUser({
          id: decoded.userId,
          name: decoded.name,
          email: decoded.email,
        });

        // Optionally, set the token in axios headers for authenticated requests
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      } else {
        throw new Error('Invalid JWT token');
      }
    } catch (error) {
      console.error('Error during sign-in:', error);
      Alert.alert('Authentication Error', error.message || 'Failed to authenticate.');
    }
  };

  /**
   * Function to handle user sign-out
   */
  const signOut = async () => {
    try {
      setAuthToken(null);
      setUser(null);
      await SecureStore.deleteItemAsync(SIGNIN_KEY);
      console.log('Token removed successfully.');

      // Remove the token from axios headers
      delete axios.defaults.headers.common['Authorization'];
    } catch (error) {
      console.error('Error during sign-out:', error);
      Alert.alert('Error', 'Failed to log out.');
    }
  };

  /**
   * Function to load the token from SecureStore on app start
   */
  const loadToken = async () => {
    try {
      const token = await SecureStore.getItemAsync(SIGNIN_KEY);
      if (token && token.split('.').length === 3) { // Basic JWT structure validation
        setAuthToken(token);
        console.log('Token loaded from SecureStore:', token); // Debugging

        // Decode the token to extract user information
        const decoded = jwtDecode(token);
        setUser({
          id: decoded.userId,
          name: decoded.name,
          email: decoded.email,
        });

        // Set the token in axios headers
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      } else if (token) {
        console.warn('Stored token is invalid. Clearing it.');
        await SecureStore.deleteItemAsync(SIGNIN_KEY);
      } else {
        console.log('No token found.');
      }
    } catch (e) {
      console.log('Failed to load token:', e);
      Alert.alert('Loading Error', 'Failed to load authentication token.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadToken();
  }, []);

  return (
    <AuthContext.Provider value={{ authToken, user, loading, signIn, signOut }}>
      {!loading && children}
    </AuthContext.Provider>
  );
};