(function($) {
    "use strict";

    function productSearch(form, query, currentQuery, timeout) {
        var search = form.find('.search'),
            category = form.find('.category'),
            nonce = form.find('input[name="search_nonce"]').val();

        // Clear previous results
        form.next('.searchresultsget').html('').removeClass('active');

        // Trim and validate query
        query = query.trim();

        if (query.length >= 3) {
            if (timeout) {
                clearTimeout(timeout);
            }

            form.next('.searchresultsget').removeClass('empty');
            search.parent().addClass('loading');

            if (query !== currentQuery) {
                timeout = setTimeout(function() {
                    // Validate category value - must be numeric or empty and exist in dropdown
                    var categoryVal = category.val();
                    var validCategories = category.find('option').map(function() { return $(this).val(); }).get();
                    if (categoryVal && (!/^\d+$/.test(categoryVal) || !validCategories.includes(categoryVal))) {
                        console.error('Invalid category value');
                        search.parent().removeClass('loading');
                        form.next('.searchresultsget').html('<div class="error">Invalid category selected.</div>').addClass('active');
                        return;
                    }

                    // Validate nonce exists
                    if (!nonce) {
                        console.error('Security nonce missing');
                        search.parent().removeClass('loading');
                        form.next('.searchresultsget').html('<div class="error">Security error. Please refresh the page.</div>').addClass('active');
                        return;
                    }

                    $.ajax({
                        url: opt.ajaxUrl,
                        type: 'POST',
                        timeout: 10000, // 10 second timeout
                        data: {
                            action: 'search_product',
                            keyword: query,
                            category: categoryVal,
                            search_nonce: nonce
                        },
                        beforeSend: function(xhr) {
                            // Additional security: set custom header
                            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                        },
                        success: function(response) {
                            currentQuery = query;
                            search.parent().removeClass('loading');

                            if (!form.next('.searchresultsget').hasClass('empty')) {
                                if (response.success === false) {
                                    // Handle JSON error response from server
                                    form.next('.searchresultsget').html('<div class="error">' + (response.data.message || 'Search failed. Please try again.') + '</div>').addClass('active');
                                } else if (response && response.length > 0) {
                                    // Sanitize the response data before inserting
                                    var sanitizedData = $('<div>').html(response).html();
                                    form.next('.searchresultsget').html('<ul>' + sanitizedData + '</ul>').addClass('active');
                                } else {
                                    form.next('.searchresultsget').html('<div class="no-results">' + opt.noResults + '</div>').addClass('active');
                                }
                            }

                            clearTimeout(timeout);
                            timeout = false;
                        },
                        error: function(xhr, status, error) {
                            currentQuery = query;
                            search.parent().removeClass('loading');

                            var errorMessage = 'Search failed. Please try again.';

                            // Handle different error types
                            if (status === 'timeout') {
                                errorMessage = 'Search timed out. Please try again.';
                            } else if (xhr.status === 400) {
                                errorMessage = xhr.responseJSON?.data?.message || 'Invalid search parameters.';
                            } else if (xhr.status === 403) {
                                errorMessage = 'Access denied. Please refresh the page.';
                            } else if (xhr.status === 500) {
                                errorMessage = 'Server error. Please try again later.';
                            }

                            form.next('.searchresultsget').html('<div class="error">' + errorMessage + '</div>').addClass('active');

                            clearTimeout(timeout);
                            timeout = false;

                            // Log error for debugging (only in development)
                            if (typeof console !== 'undefined' && console.error) {
                                console.error('Search AJAX Error:', status, error, xhr.responseText);
                            }
                        }
                    });
                }, 500);
            }
        } else {
            search.parent().removeClass('loading');
            form.next('.searchresultsget').empty().removeClass('active').addClass('empty');
            clearTimeout(timeout);
            timeout = false;
        }
    }

    // Initialize search forms when document is ready
    $(document).ready(function() {
        $('form[name="product-search"]').each(function() {
            var form = $(this),
                search = form.find('.search'),
                category = form.find('.category'),
                currentQuery = '',
                timeout = false;

            // Validate required elements exist
            if (!search.length) {
                console.error('Search input not found in form');
                return;
            }

            // Category change handler
            category.on('change', function() {
                currentQuery = '';
                var query = search.val();
                productSearch(form, query, currentQuery, timeout);
            });

            // Search input handler with debouncing
            search.on('input keyup paste', function(e) {
                var query = $(this).val();

                // Clear results on escape key
                if (e.keyCode === 27) {
                    form.next('.searchresultsget').empty().removeClass('active').addClass('empty');
                    return;
                }

                productSearch(form, query, currentQuery, timeout);
            });

            // Focus handler to show recent results
            search.on('focus', function() {
                var query = $(this).val();
                if (query.length >= 3 && form.next('.searchresultsget').html()) {
                    form.next('.searchresultsget').addClass('active');
                }
            });

            // Click outside to hide results
            $(document).on('click', function(e) {
                if (!form.is(e.target) && form.has(e.target).length === 0) {
                    form.next('.searchresultsget').removeClass('active');
                }
            });

            // Form submission handler
            form.on('submit', function(event) {
                event.preventDefault();

                var query = search.val().trim(),
                    categoryVal = category.val(),
                    getvals = '';

                // Validate inputs before redirect
                if (query && query.length > 0) {
                    // Sanitize query for URL
                    query = encodeURIComponent(query);
                    getvals = '&s=' + query;
                }

                // Validate category if provided
                var validCategories = category.find('option').map(function() { return $(this).val(); }).get();
                if (categoryVal && (!/^\d+$/.test(categoryVal) || !validCategories.includes(categoryVal))) {
                    console.error('Invalid category selected');
                    form.next('.searchresultsget').html('<div class="error">Invalid category selected.</div>').addClass('active');
                    return false;
                }

                if (categoryVal) {
                    getvals += '&product_cat=' + encodeURIComponent(categoryVal);
                }

                // Construct URL and redirect
                var baseUrl = window.location.protocol + '//' + window.location.host + window.location.pathname;
                var url = baseUrl + '?post_type=product' + getvals;

                window.location.href = url;

                return false;
            });

            // Handle result clicks
            form.next('.searchresultsget').on('click', 'a', function(e) {
                // Allow normal link behavior but hide results
                form.next('.searchresultsget').removeClass('active');
            });
        });

        // Handle search button clicks
        $('.csearchbtn').on('click', function(e) {
            e.preventDefault();
            $(this).closest('form').trigger('submit');
        });
    });

    // Additional security: Clear search results when navigating away
    $(window).on('beforeunload', function() {
        $('.searchresultsget').empty().removeClass('active');
    });

})(jQuery);