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

//#region src/components/overlays/NewNotifications/NotificationsContext/use-notifications.ts
const DISMISS_EVENT_NAME = "cube:notification:dismiss";
function useNotifications(rootRef) {
	const idPrefix = useMemo(() => (/* @__PURE__ */ new Date()).getTime(), []);
	const idRef = useRef(0);
	const listeners = useRef([]);
	const [notifications, setNotifications] = useState(/* @__PURE__ */ new Map());
	const addToast = Object.assign(useEvent((props) => {
		const nextID = idRef.current++;
		const { id = `${idPrefix}_${nextID}`, duration, isDismissible = true, ...rest } = props;
		setNotifications((toasts) => {
			const newToasts = new Map(toasts);
			newToasts.set(id, {
				id,
				isDismissible,
				duration: duration ?? (isDismissible ? 5e3 : null),
				...rest
			});
			return newToasts;
		});
		return {
			id,
			remove: () => removeToast(id),
			update: (props) => updateToast(id, props)
		};
	}), {
		success: (props) => addToast({
			type: "success",
			...props
		}),
		danger: (props) => addToast({
			type: "danger",
			...props
		}),
		attention: (props) => addToast({
			type: "attention",
			...props
		})
	});
	const updateToast = useEvent((id, props) => {
		setNotifications((toasts) => {
			const currentToast = toasts.get(id);
			if (currentToast) {
				const newToasts = new Map(toasts);
				newToasts.set(id, {
					...currentToast,
					...props
				});
				return newToasts;
			}
			return toasts;
		});
	});
	const removeToast = useEvent((id) => {
		setNotifications((toasts) => {
			if (toasts.has(id)) {
				const newToasts = new Map(toasts);
				newToasts.delete(id);
				return newToasts;
			}
			return toasts;
		});
	});
	const onDismissNotification = useEvent((id) => {
		const toast = notifications.get(id);
		if (toast == null) return;
		if (toast?.putNotificationInDropdownOnDismiss !== false) rootRef?.current?.dispatchEvent(new CustomEvent(DISMISS_EVENT_NAME, { detail: toast }));
	});
	const addOnDismissListener = useEvent((listener) => {
		const callback = (e) => listener(e.detail);
		const unsub = () => rootRef?.current?.removeEventListener(DISMISS_EVENT_NAME, callback);
		listeners.current.push(unsub);
		rootRef?.current?.addEventListener(DISMISS_EVENT_NAME, callback);
		return unsub;
	});
	useEffect(() => () => listeners.current.forEach((cb) => cb()), []);
	return {
		api: useMemo(() => ({
			notify: addToast,
			update: updateToast,
			remove: removeToast
		}), []),
		notifications: useMemo(() => [...notifications.values()], [notifications]),
		onDismissNotification,
		addOnDismissListener
	};
}

//#endregion
export { useNotifications };
//# sourceMappingURL=use-notifications.js.map