import { useEffect, useState } from "react";
import { getCachedParsedProfile } from "../utils/profileServiceCache";
/**
 * Hook to load and cache rich text profiles
 * Uses simplified service-level caching for parsed profiles
 */
export function useRichTextProfile(profilePath, serviceCall, options = {}) {
    const { enabled = true, onError } = options;
    const [state, setState] = useState({
        profilePath,
        profile: null,
        loading: false,
        error: null,
    });
    useEffect(() => {
        if (!enabled) {
            return;
        }
        if (profilePath === undefined) {
            setState({
                profilePath,
                profile: null,
                loading: false,
                error: null,
            });
            return;
        }
        let cancelled = false;
        const loadProfile = async () => {
            setState((prev) => ({
                profilePath,
                profile: prev.profilePath === profilePath ? prev.profile : null,
                loading: true,
                error: null,
            }));
            try {
                const parsedProfile = await getCachedParsedProfile(profilePath, serviceCall);
                if (cancelled)
                    return;
                setState({
                    profilePath,
                    profile: parsedProfile,
                    loading: false,
                    error: null,
                });
            }
            catch (error) {
                if (cancelled)
                    return;
                const errorObj = error instanceof Error ? error : new Error("Failed to load profile");
                setState({
                    profilePath,
                    profile: null,
                    loading: false,
                    error: errorObj,
                });
                if (onError) {
                    onError(errorObj);
                }
                else {
                    console.error("RTE loadProfile - error:", errorObj);
                }
            }
        };
        loadProfile();
        return () => {
            cancelled = true;
        };
    }, [enabled, profilePath, serviceCall, onError]);
    if (state.profilePath !== profilePath) {
        return {
            profilePath,
            profile: null,
            loading: false,
            error: null,
        };
    }
    return state;
}
/**
 * Hook that returns the fully parsed profile object
 * This is now the main hook to use for rich text profiles
 */
export function useRichTextProfileParsed(profilePath, serviceCall, options = {}) {
    const { profile, loading, error } = useRichTextProfile(profilePath, serviceCall, options);
    return {
        profile,
        loading,
        error,
    };
}
//# sourceMappingURL=useRichTextProfile.js.map