jQuery(document).ready(function($) {

    // Get parameter from URl 
    const urlParams = new URLSearchParams(window.location.search);
    const searchTerm = urlParams.get('search');

    // Check if search term exists
    if(searchTerm){
        searchPosts(searchTerm); // Call search function
        $("#search-term").val(searchTerm); // Set search term in input field
    }

    // Function to get posts
    function searchPosts(term){
        $('#loading-indicator').show(); // Show loading indicator
        $('.search-result').hide(); // Hide search result
        $('.search-no-result').hide(); // Hide no result message
        $('#search-results-container').html(''); // Clear search result
        $('.search-overlay-page').toggleClass('active'); // Show search overlay

        $.ajax({
            type: 'POST',
            url: customSearch.ajaxurl,
            data: {
                action: 'simple_product_search',
                searchTerm: term,
            },
            success: function(response) {
                $('.search-result').show(); // Hide loading indicator
                $('#search-value').text(term); // Show search result
                $('.search-overlay-page').toggleClass('active'); // Hide search overlay
            
                // If no result found
                if (response.length == 0) {
                    $('.search-no-result').show();
                }

                
                $('#loading-indicator').hide(); // Hide loading indicator
                $('#search-results-container').html(response); // Show search result

                return false;
            }
        });
    }

    $('#search-form').submit(function(e) {
        var searchTerm = $('#search').val(); // Get search term from input field

        // Check if search term is less than 3 characters
        if (searchTerm.length < 3) {
            alert('Minimum 3 karaktera za pretragu!');
            return false;
        }
    });
});