import React, { createContext, useContext, useState, useEffect, useCallback } from 'react' import { trpc } from './trpc-client' import { useNavigate } from '@tanstack/react-router' interface Staff { id: number name: string } interface AuthState { staff: Staff | null isAuthenticated: boolean isLoading: boolean token: string | null } interface AuthContextType extends AuthState { login: (name: string, password: string) => Promise logout: () => void isLoggingIn: boolean loginError: string | null } const AuthContext = createContext(undefined) export function AuthProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState({ staff: null, isAuthenticated: false, isLoading: true, token: null, }) const [loginError, setLoginError] = useState(null) const navigate = useNavigate() const loginMutation = trpc.admin.staffUser.login.useMutation() useEffect(() => { const storedToken = localStorage.getItem('auth_token') if (storedToken) { setState((prev) => ({ ...prev, token: storedToken, isAuthenticated: true, isLoading: false, })) } else { setState((prev) => ({ ...prev, isLoading: false })) } }, []) const login = useCallback( async (name: string, password: string) => { setLoginError(null) try { const data = await loginMutation.mutateAsync({ name, password }) localStorage.setItem('auth_token', data.token) setState({ staff: data.staff, token: data.token, isAuthenticated: true, isLoading: false, }) } catch (error) { setLoginError((error as Error).message || 'Login failed') throw error } }, [loginMutation] ) const logout = useCallback(() => { localStorage.removeItem('auth_token') setState({ staff: null, token: null, isAuthenticated: false, isLoading: false, }) navigate({ to: '/login' }) }, [navigate]) return ( {children} ) } export function useAuth() { const context = useContext(AuthContext) if (!context) { throw new Error('useAuth must be used within AuthProvider') } return context }