// zustand/receiptStore.ts
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';

type PreferenceItemMap = {
    [key: string]: {
        value: unknown;
    };
};

type PreferenceStore = {
    items: PreferenceItemMap;
    toggle: (key: string) => void;
    set: (key: string, value: unknown) => void;
    reset: () => void;
};

export const usePreferencesStore = create<PreferenceStore>()(
    persist(
        (set) => ({
            items: {},
            reset: () => set({ items: {} }),
            toggle: (key) => {
                return set((state) => {
                    const current = state.items[key]?.value || false;
                    return {
                        items: {
                            ...state.items,
                            [key]: { value: !current }
                        }
                    }
                })
            },
            set: (key: string, value: unknown) => {
                return set((state) => {
                    return {
                        items: {
                            ...state.items,
                            [key]: { value: value }
                        }
                    }
                })
            },
        }),
        {
            name: 'preference-storage',
            storage: createJSONStorage(() => {
                if (typeof window !== 'undefined') {
                    return localStorage;
                }
                return {
                    getItem: () => null,
                    setItem: () => { },
                    removeItem: () => { },
                };
            }),
        }
    )
);
