import {createReduxStore, register} from '@wordpress/data';

const DEFAULT_STATE = {
    blocks: [],
    imageCredit: {
        seoaic_images_credit_limit: 0,
        seoaic_images_credit: 0,
    },
};

const store = createReduxStore('SEOAIBlocks', {
    reducer: (state = DEFAULT_STATE, action) => {
        switch (action.type) {
            case 'SET_BLOCK_LOADING':
                return {
                    ...state,
                    blocks: {
                        ...state.blocks,
                        [action.item]: action.isLoading,
                    },
                };
            case 'SET_IMAGE_CREDIT':
                return {
                    ...state,
                    imageCredit: action.updatedValues,
                };
            default:
                return state;
        }
    },
    actions: {
        setBlockLoading(item, isLoading) {
            return {
                type: 'SET_BLOCK_LOADING',
                item,
                isLoading
            };
        },
        setImageCredit(updatedValues) {
            return {
                type: 'SET_IMAGE_CREDIT',
                updatedValues,
            };
        },
    },
    selectors: {
        getBlockLoading(state, item) {
            const {blocks} = state;
            const loading = blocks[item] ?? false;

            return loading;
        },
        getImageCredit(state) {
            return state.imageCredit;
        },
    },
});

register(store);

export default store;
