import { createFocusTrap } from 'focus-trap';
import { Children, cloneElement, isValidElement, useEffect, useRef } from 'react';
export const FocusTrap = ({ active, focusTrapOptions, children }) => {
    const elementRef = useRef(null);
    const trapRef = useRef(null);
    useEffect(() => {
        if (!active) {
            if (trapRef.current) {
                trapRef.current.deactivate();
                trapRef.current = null;
            }
            return;
        }
        const node = elementRef.current;
        if (!node)
            return;
        const trap = createFocusTrap(node, focusTrapOptions);
        trapRef.current = trap;
        trap.activate();
        return () => {
            trap.deactivate();
            if (trapRef.current === trap) {
                trapRef.current = null;
            }
        };
        // focus-trap-react only (re)creates the trap on active toggle; options are read at
        // creation time only, matching that behavior.
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [active]);
    const child = Children.only(children);
    if (!isValidElement(child)) {
        throw new Error('FocusTrap: children must be a single valid React element.');
    }
    const originalRef = child.props.ref;
    const mergedRef = (node) => {
        elementRef.current = node;
        if (typeof originalRef === 'function') {
            originalRef(node);
        }
        else if (originalRef && typeof originalRef === 'object' && 'current' in originalRef) {
            originalRef.current = node;
        }
    };
    return cloneElement(child, { ref: mergedRef });
};
//# sourceMappingURL=focus-trap.js.map