"use client"; import { createContext, useContext, useEffect, useState, type ReactNode, } from "react"; import { initKeycloak, logout as keycloakLogout, getUserInfo, isAuthenticated as isKeycloakAuthenticated, } from "@/lib/keycloak-client"; interface AuthContextType { isAuthenticated: boolean; isLoading: boolean; userInfo: any; logout: () => Promise; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { const [isAuthenticated, setIsAuthenticated] = useState(false); const [isLoading, setIsLoading] = useState(true); const [userInfo, setUserInfo] = useState(null); useEffect(() => { let mounted = true; async function initAuth() { try { const authenticated = await initKeycloak(); if (mounted) { setIsAuthenticated(authenticated); setIsLoading(false); if (authenticated) { setUserInfo(getUserInfo()); } } } catch (error) { console.error("Auth initialization failed:", error); if (mounted) { setIsLoading(false); } } } initAuth(); return () => { mounted = false; }; }, []); const handleLogout = async () => { await keycloakLogout(); setIsAuthenticated(false); setUserInfo(null); }; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error("useAuth must be used within an AuthProvider"); } return context; }