import { mountStoreDevtool } from 'simple-zustand-devtools';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

// Immutable default settings
const defaultSettings = {
    genAlphaSlang: false,
    // Add more settings here
};

const useLocalSettingsStore = create(
    persist(
        (set, get) => ({
            settings: { ...defaultSettings }, // clone to avoid shared reference

            // Get a setting by key
            getSetting: (key) => {
                const currentSettings = get().settings;
                return key in currentSettings ? currentSettings[key] : (defaultSettings[key] ?? null);
            },

            // Set or update a specific setting
            setSetting: (key, value) => {
                console.log(`Updating setting ${key} to`, value); // <-- Debug log
                set((state) => ({
                    settings: {
                        ...state.settings,
                        [key]: value,
                    },
                }));
            },

            // Reset all settings to default
            resetSettings: () => {
                set({ settings: { ...defaultSettings } }); // create new object reference
            },

            // Reset a specific setting to its default
            resetSetting: (key) => {
                set((state) => ({
                    settings: {
                        ...state.settings,
                        [key]: defaultSettings[key],
                    },
                }));
            },

            // Merge default settings with current ones (useful on load)
            initializeSettings: () => {
                set((state) => ({
                    settings: {
                        ...defaultSettings,
                        ...state.settings,
                    },
                }));
            },
        }),
        {
            name: 'local-settings-storage',
            // Ensure only the 'settings' key is stored
            partialize: (state) => ({ settings: state.settings }),
            // Explicit localStorage usage (for compatibility)
            storage: {
                getItem: (name) => {
                    const stored = localStorage.getItem(name);
                    return stored ? JSON.parse(stored) : null;
                },
                setItem: (name, value) => {
                    localStorage.setItem(name, JSON.stringify(value));
                },
                removeItem: (name) => {
                    localStorage.removeItem(name);
                },
            },
        },
    ),
);

if (import.meta.env.APP_ENV === 'local') {
    mountStoreDevtool('LocalSettingsStore', useLocalSettingsStore);
}

export default useLocalSettingsStore;
