import { useCallback, useEffect } from 'react';

/**
 * Shared hook for overlay behavior (escape key, scroll lock, click handling)
 *
 * Provides consistent overlay interaction patterns across Modal, Drawer,
 * CommandPalette, and other overlay-based components.
 *
 * @example
 * ```tsx
 * const { handleOverlayClick, handleEscKey } = useOverlay({
 *   isOpen,
 *   onClose,
 *   closeOnEsc: true,
 *   closeOnOverlayClick: true,
 * });
 *
 * return (
 *   <div onClick={handleOverlayClick}>
 *     <div onClick={(e) => e.stopPropagation()}>
 *       Content
 *     </div>
 *   </div>
 * );
 * ```
 */
const useOverlay = ({ isOpen, onClose, closeOnEsc = true, closeOnOverlayClick = true, enableScrollLock = true, onOverlayClick, onEscapeKey, }) => {
    // Handle overlay click
    const handleOverlayClick = useCallback((event) => {
        // Allow custom handler to run first
        onOverlayClick === null || onOverlayClick === void 0 ? void 0 : onOverlayClick(event);
        // Default close behavior: only close if clicking the overlay itself,
        // not child elements (event.target === event.currentTarget)
        if (event.target === event.currentTarget && closeOnOverlayClick) {
            onClose();
        }
    }, [closeOnOverlayClick, onClose, onOverlayClick]);
    // Handle ESC key
    const handleEscKey = useCallback((event) => {
        // Allow custom handler to run first
        onEscapeKey === null || onEscapeKey === void 0 ? void 0 : onEscapeKey(event);
        // Default close behavior
        if (event.key === 'Escape' && closeOnEsc) {
            onClose();
        }
    }, [closeOnEsc, onClose, onEscapeKey]);
    // Setup event listeners and scroll lock
    useEffect(() => {
        if (isOpen) {
            // Add Escape key listener
            document.addEventListener('keydown', handleEscKey);
            // Lock body scroll to prevent background scrolling
            if (enableScrollLock) {
                document.body.style.overflow = 'hidden';
            }
            // Cleanup on unmount or when overlay closes
            return () => {
                document.removeEventListener('keydown', handleEscKey);
                if (enableScrollLock) {
                    document.body.style.overflow = 'unset';
                }
            };
        }
    }, [isOpen, handleEscKey, enableScrollLock]);
    return {
        handleOverlayClick,
        handleEscKey,
    };
};

export { useOverlay };
