"use client"; import React, { createContext, useContext, useState, useEffect, useCallback } from "react"; import { getMe, login as apiLogin, type User } from "./api"; interface AuthContextType { user: User | null; login: (rut: string, password: string) => Promise; logout: () => void; isAuthenticated: boolean; isLoading: boolean; } const AuthContext = createContext({ user: null, login: async () => {}, logout: () => {}, isAuthenticated: false, isLoading: true, }); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const token = localStorage.getItem("helpdesk_token"); if (token) { getMe() .then((u) => setUser(u)) .catch(() => localStorage.removeItem("helpdesk_token")) .finally(() => setIsLoading(false)); } else { setIsLoading(false); } }, []); const login = useCallback(async (rut: string, password: string) => { const result = await apiLogin(rut, password); if (!result.success || !result.token) { throw new Error(result.message || "Credenciales inválidas"); } localStorage.setItem("helpdesk_token", result.token); if (result.user) setUser(result.user); }, []); const logout = useCallback(() => { localStorage.removeItem("helpdesk_token"); setUser(null); }, []); return ( {children} ); } export function useAuth() { return useContext(AuthContext); }