import { useCallback, useState } from 'react';
import { LearnResponse, LearnRequest } from '../types';
const API_BASE = import.meta.env.DEV
? 'http://localhost:37778'
: '/api';
export function useLearn() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<LearnResponse | null>(null);
const learn = useCallback(async (request: LearnRequest): Promise<LearnResponse | null> => {
setLoading(true);
setError(null);
setSuccess(null);
try {
const response = await fetch(`${API_BASE}/learn`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
const data: LearnResponse = await response.json();
if (!response.ok || data.error) {
throw new Error(data.error || `HTTP ${response.status}`);
}
setSuccess(data);
setLoading(false);
return data;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Unknown error';
setError(errorMsg);
setLoading(false);
return null;
}
}, []);
const reset = useCallback(() => {
setLoading(false);
setError(null);
setSuccess(null);
}, []);
return {
loading,
error,
success,
learn,
reset,
};
}