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

//#region src/components/overlays/Notifications/use-notifications.ts
let ownerIdCounter = 0;
function generateOwnerId() {
	ownerIdCounter += 1;
	return `notif-owner-${ownerIdCounter}-${Date.now()}`;
}
function isStoredMode(options) {
	return options.mode === "stored";
}
/**
* Hook to display and manage notifications.
*
* Each hook instance acts as an owner scope:
* - `notify()` created from this instance attaches ownership metadata.
* - On unmount, all attached visible overlay notifications are dismissed.
* - On unmount, all attached persistent records are also removed.
* - `notify()`/`dismiss()` calls from stale closures after unmount are no-ops.
*
* @example
* ```tsx
* const { notify, record, dismiss } = useNotifications();
*
* notify({
*   id: 'deploy:123',
*   theme: 'success',
*   title: 'Deployment completed',
*   description: 'Version 1.4.2 is live.',
*   actions: (
*     <>
*       <Notification.Action onPress={() => openLogs()}>View logs</Notification.Action>
*       <Notification.Action onPress={() => openDeployment()}>Open</Notification.Action>
*     </>
*   ),
* });
*
* // Store directly to persistent list (no overlay)
* record({
*   id: 'server:alert-1',
*   theme: 'warning',
*   title: 'Server alert',
* });
* ```
*/
function useNotifications() {
	const { addNotification, removeNotification, addPersistentItem, removePersistentItem, removeByOwner, removePersistentItemsByOwner } = useNotificationContext();
	const ownerIdRef = useRef(generateOwnerId());
	const isMountedRef = useRef(true);
	const cleanupTimerRef = useRef(null);
	const lastOptionsRef = useRef(null);
	useWarn(lastOptionsRef.current && "persistent" in lastOptionsRef.current && lastOptionsRef.current.persistent === true && lastOptionsRef.current.id == null, {
		once: false,
		key: ["Notification", "persistent-without-id"],
		args: ["Notification: `persistent: true` requires an explicit `id` for reliable dedupe/upsert."]
	});
	useWarn(lastOptionsRef.current?.mode === "stored" && lastOptionsRef.current.id == null, {
		once: false,
		key: ["Notification", "stored-without-id"],
		args: ["Notification: `mode: \"stored\"` should have an explicit `id` for reliable upsert."]
	});
	const storedIdCounter = useRef(0);
	const createStoredHandle = useEvent((options) => {
		storedIdCounter.current += 1;
		const now = Date.now();
		const id = options.id ?? `stored-${storedIdCounter.current}-${now}`;
		const createdAt = options.createdAt ?? now;
		addPersistentItem({
			id,
			theme: options.theme,
			title: options.title,
			description: options.description,
			icon: options.icon,
			actions: options.actions ?? void 0,
			createdAt,
			updatedAt: createdAt,
			ownerId: ownerIdRef.current
		});
		return {
			id,
			dismiss: () => {
				removePersistentItem(id);
			}
		};
	});
	const notify = useEvent((options) => {
		if (!isMountedRef.current) return {
			id: options.id ?? "",
			dismiss: () => {}
		};
		lastOptionsRef.current = options;
		if (isStoredMode(options)) return createStoredHandle(options);
		const notificationId = addNotification({
			...options,
			mode: "overlay"
		}, ownerIdRef.current);
		return {
			id: notificationId,
			dismiss: () => {
				if (isMountedRef.current) removeNotification(notificationId, "api");
			}
		};
	});
	const record = useEvent((options) => {
		if (!isMountedRef.current) return {
			id: options.id ?? "",
			dismiss: () => {}
		};
		lastOptionsRef.current = {
			...options,
			mode: "stored"
		};
		return createStoredHandle(options);
	});
	const dismiss = useEvent((id) => {
		if (!isMountedRef.current) return;
		removeNotification(id, "api");
	});
	useEffect(() => {
		isMountedRef.current = true;
		if (cleanupTimerRef.current) {
			clearTimeout(cleanupTimerRef.current);
			cleanupTimerRef.current = null;
		}
		return () => {
			isMountedRef.current = false;
			cleanupTimerRef.current = setTimeout(() => {
				removeByOwner(ownerIdRef.current);
				removePersistentItemsByOwner(ownerIdRef.current);
			}, 0);
		};
	}, [removeByOwner, removePersistentItemsByOwner]);
	return {
		notify,
		record,
		dismiss
	};
}

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