/* @oracle/oraclejet-preact: undefined */
import { useState, useRef, useMemo, useEffect } from 'preact/hooks';
import { u as useReorderableContext } from './useReorderableContext-79b1c941.js';

/**
 * This hook converts the new API (i.e. currentItemOverride and onPersistCurrentItem) back to
 * the old API (i.e. currentKey and onCurrentKeyChange), keeps the internal current item, and
 * also triggers an update when a new currentItemOverride is passed by the app
 *
 * @param currentItemOverride
 * @param onPersistCurrentItem
 */
const useCurrentItemOverride = (currentItemOverride, onPersistCurrentItem) => {
    // the internal state of current item
    const [currentItem, setCurrentItem] = useState();
    // track the currentItemOverride props
    const currentItemOverrideRef = useRef();
    // whether the current item is overridden by the app
    const isCurrentItemOverridden = useRef(false);
    // if reorder is enabled, need to update the context here when current item is changed
    const reorderContext = useReorderableContext();
    // intercept onPersistCurrentItem calls to ensure internal state is updated appropriately
    const handleCurrentItemChanged = useMemo(() => {
        return (detail) => {
            const rowKey = detail.value;
            setCurrentItem({ rowKey });
            onPersistCurrentItem?.(detail);
            if (reorderContext?.currentItemKey != null) {
                reorderContext.currentItemKey.current = rowKey;
            }
        };
    }, [onPersistCurrentItem, reorderContext?.currentItemKey]);
    // ensure any new currentItemOverride settings are applied only on that render
    // (same as how Table handles the changes)
    if (currentItemOverrideRef.current !== currentItemOverride) {
        currentItemOverrideRef.current = currentItemOverride;
        if (currentItem?.rowKey !== currentItemOverride?.rowKey) {
            isCurrentItemOverridden.current = true;
            handleCurrentItemChanged({ value: currentItemOverride?.rowKey });
        }
    }
    useEffect(() => {
        isCurrentItemOverridden.current = false;
    });
    return {
        currentKey: currentItem?.rowKey,
        onCurrentKeyChange: handleCurrentItemChanged,
        isCurrentItemOverridden: isCurrentItemOverridden.current
    };
};

export { useCurrentItemOverride as u };
//# sourceMappingURL=useCurrentItemOverride-43ef8f59.js.map
