import React, { createContext, useContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; interface AuthContextType { isAuthenticated: boolean | null; username: string | null; login: (token: string) => void; logout: () => Promise; } const AuthContext = createContext({ isAuthenticated: null, username: null, login: () => {}, logout: async () => {}, }); export function AuthProvider({ children }: { children: React.ReactNode }) { const [isAuthenticated, setIsAuthenticated] = useState(null); const [username, setUsername] = useState(null); const decodeJwt = (token: string): string | null => { try { const base64Payload = token.split('.')[1]; const payload = JSON.parse(atob(base64Payload)); return payload.sub || null; } catch { return null; } }; useEffect(() => { AsyncStorage.getItem('jwt_token').then(token => { if (token) { setUsername(decodeJwt(token)); setIsAuthenticated(true); } else { setIsAuthenticated(false); } }); }, []); const login = (token: string) => { setUsername(decodeJwt(token)); setIsAuthenticated(true); }; const logout = async () => { await AsyncStorage.removeItem('jwt_token'); setUsername(null); setIsAuthenticated(false); }; return ( {children} ); } export const useAuth = () => useContext(AuthContext);