import { useState, useEffect } from 'react';
import { getFearAndGreed, getVix, getTreasury10Y, getWTI } from '../../../api';

export default function useMarketContext(shouldLoad) {
    const [marketCtx, setMarketCtx] = useState(null);

    useEffect(() => {
        if (!shouldLoad || marketCtx !== null) return;
        Promise.allSettled([getFearAndGreed(), getVix(), getTreasury10Y(), getWTI()])
            .then(([fg, vix, t, w]) => {
                const fgRaw = fg.status === 'fulfilled' ? fg.value : null;
                const fgScore = fgRaw?.fear_and_greed?.score ?? fgRaw?.score;
                setMarketCtx({
                    fg: fgScore != null ? Math.round(Number(fgScore)) : null,
                    vix: vix.status === 'fulfilled' ? (vix.value?.value ?? null) : null,
                    treasury: t.status === 'fulfilled' ? (t.value?.value ?? null) : null,
                    wti: w.status === 'fulfilled' ? (w.value?.value ?? null) : null,
                });
            });
    }, [shouldLoad, marketCtx]);

    return marketCtx;
}
