import { createContext, useContext, useState, useEffect } from 'react' import type { ReactNode } from 'react' import { authApi } from '../api/client' interface User { id: number email: string first_name: string last_name: string is_active: boolean roles: string[] module_roles: Record } interface AuthContextType { user: User | null loading: boolean login: (email: string, password: string) => Promise logout: () => void } const AuthContext = createContext(undefined) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { const token = localStorage.getItem('platform_token') if (token) { authApi.me() .then(res => setUser(res.data)) .catch(() => localStorage.removeItem('platform_token')) .finally(() => setLoading(false)) } else { setLoading(false) } }, []) const login = async (email: string, password: string) => { const res = await authApi.login({ email, password }) localStorage.setItem('platform_token', res.data.access_token) setUser(res.data.user) } const logout = () => { localStorage.removeItem('platform_token') setUser(null) } return ( {children} ) } export function useAuth() { const ctx = useContext(AuthContext) if (!ctx) throw new Error('useAuth must be inside AuthProvider') return ctx }