/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-45e7184
 * Released under the MIT license.
 */

import { useState } from 'react';
import { useEvent } from '../../../_internal/index.js';
// ─── Hook ────────────────────────────────────────────────────────────
export function usePersistentState(maxItems) {
    const [persistentItems, setPersistentItems] = useState([]);
    const addPersistentItem = useEvent((item) => {
        setPersistentItems((prev) => {
            // Upsert by id
            const existingIndex = prev.findIndex((i) => i.id === item.id);
            let newItems;
            if (existingIndex !== -1) {
                newItems = [...prev];
                // Updated items are marked unread again
                newItems[existingIndex] = {
                    ...newItems[existingIndex],
                    ...item,
                    isRead: false,
                };
            }
            else {
                newItems = [{ ...item, isRead: item.isRead ?? false }, ...prev];
            }
            // Enforce max cap
            if (newItems.length > maxItems) {
                newItems = newItems.slice(0, maxItems);
            }
            // Sort newest first
            newItems.sort((a, b) => b.createdAt - a.createdAt);
            return newItems;
        });
    });
    const removePersistentItem = useEvent((id) => {
        setPersistentItems((prev) => prev.filter((i) => i.id !== id));
    });
    const removePersistentItemsByOwner = useEvent((ownerId) => {
        setPersistentItems((prev) => prev.filter((i) => i.ownerId !== ownerId));
    });
    const clearPersistentItems = useEvent(() => {
        setPersistentItems([]);
    });
    const markAllAsRead = useEvent(() => {
        setPersistentItems((prev) => {
            const hasUnread = prev.some((i) => !i.isRead);
            if (!hasUnread)
                return prev;
            return prev.map((i) => (i.isRead ? i : { ...i, isRead: true }));
        });
    });
    return {
        persistentItems,
        addPersistentItem,
        removePersistentItem,
        removePersistentItemsByOwner,
        clearPersistentItems,
        markAllAsRead,
    };
}

        