document.addEventListener('DOMContentLoaded', function () {
    const toggleBtn = document.querySelector('[data-toggle-search]');
    const header = document.querySelector('.site-header');
    const searchBar = document.querySelector('.header-search-bar');
    const input = searchBar ? searchBar.querySelector('input') : null;

    if (!toggleBtn || !header || !searchBar) return;

    let isOpen = false;

    toggleBtn.addEventListener('click', function () {
        isOpen = !isOpen;
        header.classList.toggle('search-visible', isOpen);
        if (isOpen && input) {
            setTimeout(() => input.focus(), 50);
        }
    });

    document.addEventListener('click', function (e) {
        if (!isOpen) return;
        if (!searchBar.contains(e.target) && !toggleBtn.contains(e.target)) {
            isOpen = false;
            header.classList.remove('search-visible');
        }
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            isOpen = false;
            header.classList.remove('search-visible');
        }
    });

    function isHomeFilterMode() {
        return typeof window.homeProductSearch === 'function' && !!document.getElementById('products-section');
    }

    function submitOrFilter(form) {
        if (!form) return;
        const formInput = form.querySelector('input[name="q"]');
        form.addEventListener('submit', function (e) {
            const query = formInput ? formInput.value : '';
            if (isHomeFilterMode()) {
                e.preventDefault();
                isOpen = false;
                header.classList.remove('search-visible');
                window.homeProductSearch(query);
                return false;
            }
        });
        if (formInput) {
            formInput.addEventListener('input', function () {
                if (isHomeFilterMode()) {
                    window.homeProductSearch(formInput.value || '');
                }
            });
            formInput.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' && isHomeFilterMode()) {
                    e.preventDefault();
                    window.homeProductSearch(formInput.value || '');
                }
            });
        }
    }

    document.querySelectorAll('.header-search-bar form, .search-form, .mobile-menu-search form').forEach(submitOrFilter);
});
