/** @license MIT | @cube-dev/ui-kit v0.0.0-canary-e634e55 | Cube Dev Team */
import { useEvent } from "../../../_internal/hooks/use-event.js";
import { cleanupAndGetValidIds, saveDismissedId } from "./dismissed-storage.js";
import { useRef, useState } from "react";

//#region src/components/overlays/Notifications/use-persistent-state.ts
function usePersistentState(maxItems) {
	const [persistentItems, setPersistentItems] = useState([]);
	const dismissedPersistentIdsRef = useRef(null);
	if (dismissedPersistentIdsRef.current === null) dismissedPersistentIdsRef.current = cleanupAndGetValidIds();
	const fullyDismissedIdsRef = useRef(/* @__PURE__ */ new Set());
	return {
		persistentItems,
		addPersistentItem: useEvent((item) => {
			if (fullyDismissedIdsRef.current.has(String(item.id))) return;
			dismissedPersistentIdsRef.current.add(String(item.id));
			saveDismissedId(item.id);
			setPersistentItems((prev) => {
				const existingIndex = prev.findIndex((i) => i.id === item.id);
				let newItems;
				if (existingIndex !== -1) {
					newItems = [...prev];
					newItems[existingIndex] = {
						...newItems[existingIndex],
						...item,
						isRead: false
					};
				} else newItems = [{
					...item,
					isRead: item.isRead ?? false
				}, ...prev];
				if (newItems.length > maxItems) newItems = newItems.slice(0, maxItems);
				newItems.sort((a, b) => b.createdAt - a.createdAt);
				return newItems;
			});
		}),
		removePersistentItem: useEvent((id) => {
			fullyDismissedIdsRef.current.add(String(id));
			setPersistentItems((prev) => prev.filter((i) => i.id !== id));
		}),
		removePersistentItemsByOwner: useEvent((ownerId) => {
			setPersistentItems((prev) => prev.filter((i) => i.ownerId !== ownerId));
		}),
		clearPersistentItems: useEvent(() => {
			setPersistentItems([]);
		}),
		markAllAsRead: useEvent(() => {
			setPersistentItems((prev) => {
				if (!prev.some((i) => !i.isRead)) return prev;
				return prev.map((i) => i.isRead ? i : {
					...i,
					isRead: true
				});
			});
		}),
		hasDismissedPersistentId: useEvent((id) => {
			return dismissedPersistentIdsRef.current.has(String(id));
		}),
		isFullyDismissedId: useEvent((id) => {
			return fullyDismissedIdsRef.current.has(String(id));
		}),
		saveDismissedPersistentId: useEvent((id) => {
			dismissedPersistentIdsRef.current.add(String(id));
			saveDismissedId(id);
		}),
		undoFullyDismissedId: useEvent((id) => {
			fullyDismissedIdsRef.current.delete(String(id));
		}),
		removePersistentItemSilently: useEvent((id) => {
			dismissedPersistentIdsRef.current.delete(String(id));
			setPersistentItems((prev) => prev.filter((i) => i.id !== id));
		})
	};
}

//#endregion
export { usePersistentState };
//# sourceMappingURL=use-persistent-state.js.map