import create from 'zustand';

const storedProductIds = sessionStorage.getItem('selectedCompareApps');
const selectedProductIds = storedProductIds ? storedProductIds.split(',').map(productId => Number(productId)) : [];

export const [compareProductsStore] = create(set => ({
    list: selectedProductIds,
    toggle: itemId => set(state => {
        const list = [...state.list];
        const itemIndex = list.indexOf(itemId);
        // item was in the array, toggle it by removing
        if (itemIndex !== -1) {
            list.splice(itemIndex, 1);
        } else {
            list.push(itemId);
        }
        sessionStorage.setItem('selectedCompareApps', list);
        return {
            list
        };
    })
}));
