import React, { useContext, useEffect, createContext, useMemo, useState, useCallback } from "react";
import api from "./api";
const initialState = {
    isLoading: false,
    value: null,
    error: null,
};
export const rampCatalogContext = createContext({
    state: initialState,
    updateCatalog: () => Promise.resolve(),
});
export function useRampCatalogContext() {
    const context = useContext(rampCatalogContext);
    if (context === undefined) {
        throw new Error("useRampCatalog must be used within a RampCatalogProvider");
    }
    return context.state;
}
export function RampCatalogProvider({ children, updateFrequency, }) {
    const [state, setState] = useState(initialState);
    const updateCatalog = useCallback(async () => {
        setState(currentState => ({
            ...currentState,
            isLoading: true,
            error: null,
        }));
        try {
            const value = await api.fetchRampCatalog();
            setState(() => ({
                isLoading: false,
                value,
                error: null,
            }));
        }
        catch (error) {
            setState(currentState => ({
                ...currentState,
                isLoading: false,
                error,
            }));
        }
    }, []);
    const value = useMemo(() => ({
        state,
        updateCatalog,
    }), [state, updateCatalog]);
    useEffect(() => {
        const interval = setInterval(() => {
            updateCatalog();
        }, updateFrequency);
        updateCatalog();
        return () => {
            clearInterval(interval);
        };
    }, [updateFrequency, updateCatalog]);
    return React.createElement(rampCatalogContext.Provider, { value: value }, children);
}
//# sourceMappingURL=index.js.map