import { getFocusableElements, getFirstFocusable } from './focus-utils.js';
/**
 * Create a focus trap within a container element
 */
export function createFocusTrap(container, options = {}) {
    const { initialFocus = null, returnFocus = null, autoFocus = true } = options;
    let active = false;
    let previouslyFocused = null;
    function handleKeydown(event) {
        if (event.key !== 'Tab' || !active)
            return;
        const focusables = getFocusableElements(container);
        if (focusables.length === 0)
            return;
        const first = focusables[0];
        const last = focusables[focusables.length - 1];
        if (event.shiftKey) {
            // Shift + Tab: going backwards
            if (document.activeElement === first) {
                event.preventDefault();
                last.focus();
            }
        }
        else {
            // Tab: going forwards
            if (document.activeElement === last) {
                event.preventDefault();
                first.focus();
            }
        }
    }
    function activate() {
        if (active)
            return;
        active = true;
        previouslyFocused = document.activeElement;
        // Add keydown listener
        container.addEventListener('keydown', handleKeydown);
        // Focus initial element
        if (initialFocus) {
            initialFocus.focus();
        }
        else if (autoFocus) {
            const first = getFirstFocusable(container);
            if (first) {
                first.focus();
            }
        }
    }
    function deactivate() {
        if (!active)
            return;
        active = false;
        container.removeEventListener('keydown', handleKeydown);
        // Return focus
        const focusTarget = returnFocus ?? previouslyFocused;
        if (focusTarget && typeof focusTarget.focus === 'function') {
            focusTarget.focus();
        }
    }
    function isActive() {
        return active;
    }
    return { activate, deactivate, isActive };
}
/**
 * Simple focus trap function for one-off use
 */
export function focusTrap(container, options) {
    const trap = createFocusTrap(container, options);
    trap.activate();
    return () => trap.deactivate();
}
