'use client';


import { useCallback, useEffect, useMemo, useState } from "react";

//#region src/hooks/usePersistedStore.ts
const usePersistedStore = (key, initialState) => {
	const [state, setState] = useState(() => {
		if (initialState !== void 0) {
			const result = typeof initialState === "function" ? initialState() : initialState;
			if (typeof window === "undefined") return result;
			const persistedState = localStorage?.getItem(key);
			if (persistedState) try {
				return JSON.parse(persistedState);
			} catch (e) {
				console.error(e);
			}
			return result;
		}
	});
	useEffect(() => {
		const persistedState = localStorage?.getItem(key);
		if (persistedState && state === void 0) try {
			setState(JSON.parse(persistedState));
		} catch (e) {
			console.error(e);
		}
		else if (initialState !== void 0 && state === void 0) setState(initialState);
	}, [key, state]);
	/**
	* Allows setting state either directly or via a functional update.
	* If passed a function, we merge/update based on the previous state.
	*/
	const setStateWrapper = useCallback((valueOrUpdater) => {
		setState((prev) => {
			const newValue = typeof valueOrUpdater === "function" ? valueOrUpdater(prev) : valueOrUpdater;
			localStorage?.setItem(key, JSON.stringify(newValue));
			return newValue;
		});
	}, [key, setState]);
	const loadState = useCallback(() => {
		const savedState = localStorage?.getItem(key);
		if (savedState) setState(JSON.parse(savedState));
	}, [key, setState]);
	return useMemo(() => [
		state,
		setStateWrapper,
		loadState
	], [
		state,
		setStateWrapper,
		loadState
	]);
};

//#endregion
export { usePersistedStore };
//# sourceMappingURL=usePersistedStore.mjs.map