import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' import { api } from './api' import type { User } from './types' type AuthContextType = { user: User | null loading: boolean authenticate: (mode: 'login' | 'register', phone: string, password: string, contactName?: string, inviteToken?: string) => Promise adminLogin: (phone: string, password: string) => Promise logout: () => Promise setUser: (u: User) => void } const AuthContext = createContext(null!) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { const load = () => localStorage.getItem('xinghen_token') ? api .me() .then((r) => setUser(r.user)) .catch(() => setUser(null)) .finally(() => setLoading(false)) : setLoading(false) load() addEventListener('auth-expired', load) return () => removeEventListener('auth-expired', load) }, []) async function authenticate(mode: 'login' | 'register', phone: string, password: string, contactName?: string, inviteToken?: string) { const r = mode === 'register' ? await api.register(phone, password, contactName || '', inviteToken) : await api.login(phone, password) localStorage.setItem('xinghen_token', r.token) setUser(r.user) } async function adminLogin(phone: string, password: string) { const r = await api.admin.login(phone, password) localStorage.setItem('xinghen_token', r.token) setUser(r.user) return r.user } async function logout() { await api.logout().catch(() => {}) localStorage.removeItem('xinghen_token') setUser(null) } return ( {children} ) } export const useAuth = () => useContext(AuthContext)