/* @oracle/oraclejet-preact: undefined */
'use strict';

var hooks = require('preact/hooks');
var useReorderableContext = require('./useReorderableContext-92514102.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] = hooks.useState();
    // track the currentItemOverride props
    const currentItemOverrideRef = hooks.useRef();
    // whether the current item is overridden by the app
    const isCurrentItemOverridden = hooks.useRef(false);
    // if reorder is enabled, need to update the context here when current item is changed
    const reorderContext = useReorderableContext.useReorderableContext();
    // intercept onPersistCurrentItem calls to ensure internal state is updated appropriately
    const handleCurrentItemChanged = hooks.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 });
        }
    }
    hooks.useEffect(() => {
        isCurrentItemOverridden.current = false;
    });
    return {
        currentKey: currentItem?.rowKey,
        onCurrentKeyChange: handleCurrentItemChanged,
        isCurrentItemOverridden: isCurrentItemOverridden.current
    };
};

exports.useCurrentItemOverride = useCurrentItemOverride;
//# sourceMappingURL=useCurrentItemOverride-5e70159d.js.map
