const noopUnsubscribe = () => { };
const createNoopAdapter = () => ({
    getItem: () => null,
    setItem: () => { },
    removeItem: () => { },
    subscribe: () => noopUnsubscribe
});
/**
 * Default browser implementation backed by `window.localStorage`.
 * Falls back to a noop adapter when `window` is not available (e.g., SSR environments).
 */
export const createBrowserStorageAdapter = () => {
    if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
        return createNoopAdapter();
    }
    const getItem = (key) => {
        try {
            return window.localStorage.getItem(key);
        }
        catch (error) {
            console.error(`Error reading from localStorage for key "${key}":`, error);
            return null;
        }
    };
    const setItem = (key, value) => {
        try {
            window.localStorage.setItem(key, value);
        }
        catch (error) {
            console.error(`Error writing to localStorage for key "${key}":`, error);
        }
    };
    const removeItem = (key) => {
        try {
            window.localStorage.removeItem(key);
        }
        catch (error) {
            console.error(`Error removing localStorage key "${key}":`, error);
        }
    };
    const subscribe = (key, callback) => {
        const handleStorageEvent = (event) => {
            if (event.key === key) {
                callback(event.newValue);
            }
        };
        window.addEventListener('storage', handleStorageEvent);
        return () => {
            window.removeEventListener('storage', handleStorageEvent);
        };
    };
    return {
        getItem,
        setItem,
        removeItem,
        subscribe
    };
};
export const browserStorageAdapter = createBrowserStorageAdapter();
