export default function search() {
    const searchButton = '.js-header-search-button, .js-search-collapse, .js-search-input';
    const closeSearch = '.js-close-search';
    const openClass = 'open-search';
    const searchInput = document.querySelector('.js-search-input');
    const searchPopupContainer = document.querySelector('.js-search-popup');
    const searchTabbable = searchPopupContainer ? searchPopupContainer.querySelectorAll('a[href], button:not([disabled]), .js-search-input') : null;

    window.addEventListener('click', function (event) {
        if (event.target.matches(searchButton) && !event.target.matches(closeSearch)) {
            document.body.classList.add(openClass);
            searchInput.focus();

            setTabIndex('0');
        } else {
            document.body.classList.remove(openClass);

            setTabIndex('-1');
        }
    });

    function setTabIndex(tabindex) {
        if (searchTabbable && searchTabbable.length > 0) {
            searchTabbable.forEach(function (item) {
                item.setAttribute('tabindex', tabindex);
            });
        }
    }

    if (searchPopupContainer) {
        searchPopupContainer.addEventListener('keydown', (e) => {
            const focusableElements = searchPopupContainer.querySelectorAll('a[href], button:not([disabled]');
            const firstFocusableElement = focusableElements[0];
            const lastFocusableElement = focusableElements[focusableElements.length - 1];
            const isTabPressed = e.key === 'Tab';

            if (!isTabPressed) {
                return;
            }

            if (e.shiftKey) {
                if (document.activeElement === firstFocusableElement) {
                    lastFocusableElement.focus();
                    e.preventDefault();
                }
            } else {
                if (document.activeElement === lastFocusableElement) {
                    firstFocusableElement.focus();
                    e.preventDefault();
                }
            }
        });
    }
}
