"use client" import { createContext, useState, useEffect, useCallback, type ReactNode } from "react" import api from "@/lib/api" import { getTokens, setTokens, clearTokens } from "@/lib/auth" import type { AuthResponse, UserResponse } from "@/lib/types" interface AuthContextValue { user: UserResponse | null isAuthenticated: boolean isAdmin: boolean isLoading: boolean login: (email: string, password: string) => Promise register: (username: string, email: string, password: string) => Promise logout: () => void } export const AuthContext = createContext(null) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [isLoading, setIsLoading] = useState(true) useEffect(() => { const { access } = getTokens() if (!access) { setIsLoading(false) return } api .get("/auth/me") .then((res) => setUser(res.data)) .catch(() => clearTokens()) .finally(() => setIsLoading(false)) }, []) const login = useCallback(async (email: string, password: string) => { const { data } = await api.post("/auth/login", { email, password, }) setTokens(data.token, data.refresh_token) setUser(data.user) }, []) const register = useCallback( async (username: string, email: string, password: string) => { const { data } = await api.post("/auth/register", { username, email, password, }) setTokens(data.token, data.refresh_token) setUser(data.user) }, [], ) const logout = useCallback(() => { api.post("/auth/logout").catch(() => {}) clearTokens() setUser(null) window.location.href = "/login" }, []) return ( {children} ) }