'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 && persistedState !== "undefined" && 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;
			if (newValue !== "undefined") {
				localStorage?.setItem(key, JSON.stringify(newValue));
				return newValue;
			}
			return prev;
		});
	}, [key, setState]);
	const loadState = useCallback(() => {
		const savedState = localStorage?.getItem(key);
		if (savedState) setState(JSON.parse(savedState));
	}, [key, setState]);
	const clearState = useCallback(() => {
		localStorage?.removeItem(key);
		setState(void 0);
	}, [key]);
	return useMemo(() => [
		state,
		setStateWrapper,
		loadState,
		clearState
	], [
		state,
		setStateWrapper,
		loadState,
		clearState
	]);
};

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