const { registerStore } = wp.data;

const DEFAULT_STATE = {
    suggestions: {},
    loading: false
};

const actions = {
    setSuggestion(clientId, content) {
        return {
            type: 'SET_SUGGESTION',
            clientId,
            content
        };
    },
    clearSuggestion(clientId) {
        return {
            type: 'CLEAR_SUGGESTION',
            clientId
        };
    },
    setLoading(isLoading) {
        return {
            type: 'SET_LOADING',
            isLoading
        };
    }
};

function reducer(state = DEFAULT_STATE, action) {
    switch (action.type) {
        case 'SET_SUGGESTION':
            return {
                ...state,
                suggestions: {
                    ...state.suggestions,
                    [action.clientId]: action.content
                }
            };
        case 'CLEAR_SUGGESTION':
            const newSuggestions = { ...state.suggestions };
            delete newSuggestions[action.clientId];
            return {
                ...state,
                suggestions: newSuggestions
            };
        case 'SET_LOADING':
            return {
                ...state,
                loading: action.isLoading
            };
        default:
            return state;
    }
}

const selectors = {
    getSuggestion: (state, clientId) => state.suggestions[clientId] || null,
    isLoading: (state) => state.loading
};

registerStore('swpanel/ai-suggestions', {
    reducer,
    actions,
    selectors
});
