(function($, elementor) {

    'use strict';

    var widgetSearchPlus = function( $scope ) {

            var isFound = false;

            $scope.find('.tx-search-form-input').on( {
                focus: function() {
                    $scope.addClass( 'tx-search-form-input-focus' );
                },
                blur: function() {
                    $scope.removeClass( 'tx-search-form-input-focus' );
                }
            } );
            
            if ( $scope.find('.tx-category-select').length > 0 ) {
                // Set the selected value on page load
                $(document).ready(function() {
                    var txSelectedCategory = localStorage.getItem('txSelectedCategory');
                    if (txSelectedCategory) {
                        $scope.find('.tx-category-select option').each(function() {
                            if ($(this).val() === txSelectedCategory) {
                                isFound = true;
                                $scope.find('.tx-category-select').val(txSelectedCategory);
                                return false; // Breaks out of the .each() loop
                            } else {
                                $scope.find('.tx-category-select').val(0);
                            }
                        });
                    }
                });

                $scope.find('.tx-category-select').on('change', function(e) {
                    
                    var selectedValue = $(this).val();
                    localStorage.setItem('txSelectedCategory', selectedValue);

                    if ($scope.find('.tx-search-form-input').attr('ajax-search') === 'yes') {
                        postsOffset = 0;
                        $scope.find('.tx-search-plus-data-fetch').hide();
                        $scope.find('.tx-search-plus-data-fetch ul').html('');
                        ajaxSearchCall($scope.find('.tx-search-form-input'), postsOffset, e);
                    }
                });
            }

            var prevData;
            var searchTimeout = null;

            function ajaxSearchCall(thisObject, postsOffset, e) {
                if ( e.which === 13 ) {
                    return false;
                }

                if (searchTimeout != null) {
                    clearTimeout(searchTimeout);
                }
                var optionPostType = ($scope.find('.tx-category-select').length > 0 && $scope.find('.tx-category-select').find('option:selected').data('post-type'));
                var txTaxonomyType = $scope.find('.tx-search-form-input').attr('tx-taxonomy-type');

                if ( $scope.find('.tx-category-select').length > 0) {
                    if (!txTaxonomyType) {
                        if ($scope.find('.tx-search-form-input').attr('tx-query-type') == 'product') {
                            txTaxonomyType = 'product_cat';
                        } else {
                            txTaxonomyType = 'category';
                        }
                    }
                }

                searchTimeout = setTimeout(() => {
                    var thisValue = thisObject.val();
                    var excludeIds = thisObject.data('exclude-ids') || '';
                      if ( excludeIds ) {
                        excludeIds = excludeIds.toString().split(',').map(Number);
                      }

                    $.ajax({
                        type: 'POST',
                        url: TXSearchPlus.ajaxurl,
                        data: { 
                            action: 'tx_data_fetch',
                            nonce: TXSearchPlus.nonce,
                            tx_keyword: $scope.find('.tx-search-form-input').val(),
                            tx_exclude_ids:   excludeIds,
                            tx_query_type: $scope.find('.tx-search-form-input').attr('tx-query-type'),
                            tx_option_post_type: optionPostType ? $scope.find('.tx-category-select').find('option:selected').data('post-type') : '',
                            tx_taxonomy_type: txTaxonomyType,
                            tx_category: $scope.find('.tx-category-select').length > 0 ? $scope.find('.tx-category-select').val() : '',
                            tx_number_of_results: $scope.find('.tx-search-form-input').attr('number-of-results'),
                            tx_search_results_offset: postsOffset,
                            tx_show_description: $scope.find('.tx-search-form-input').attr('show-description'),
                            tx_number_of_words: $scope.find('.tx-search-form-input').attr('number-of-words'),
                            tx_show_ajax_thumbnail: $scope.find('.tx-search-form-input').attr('show-ajax-thumbnails'),
                            tx_show_product_price: $scope.find('.tx-search-form-input').attr('show-product-price'),
                            tx_show_view_result_btn: $scope.find('.tx-search-form-input').attr('show-view-result-btn'),
                            tx_view_result_text: $scope.find('.tx-search-form-input').attr('view-result-text'),
                            tx_no_results: $scope.find('.tx-search-form-input').attr('no-results'),
                            tx_exclude_without_thumb: $scope.find('.tx-search-form-input').attr('exclude-without-thumb'),
                            tx_ajax_search_link_target: $scope.find('.tx-search-form-input').attr('link-target'),
                            tx_show_ps_pt: $scope.find('.tx-search-form-input').attr('password-protected'),
                            tx_show_attachments: $scope.find('.tx-search-form-input').attr('attachments'),
                        },
                        success: function(data) {
                            $scope.closest('section').addClass('tx-section-z-index');
                            if ( $scope.find('.tx-search-plus-data-fetch ul').html() === '' ) {
                                $scope.find( '.tx-pagination-loading' ).hide();
                                $scope.find('.tx-search-plus-data-fetch ul').html( data );
                                $scope.find('.tx-no-more-results').fadeOut(100);
                                setTimeout(function() {
                                    if (!data.includes('tx-no-results')) {
                                        $scope.find('.tx-ajax-search-pagination').css('display', 'flex');
                                        if ( $scope.find('.tx-search-plus-data-fetch ul').find('li').length < $scope.find('.tx-search-form-input').attr('number-of-results') ||
                                            $scope.find('.tx-search-plus-data-fetch ul').find('li').length == $scope.find('.tx-search-plus-data-fetch ul').find('li').data('number-of-results')) {
                                            $scope.find('.tx-ajax-search-pagination').css('display', 'none');
                                            $scope.find('.tx-load-more-results').fadeOut(100);
                                        } else {
                                            $scope.find('.tx-ajax-search-pagination').css('display', 'flex');
                                            $scope.find('.tx-load-more-results').fadeIn(100);
                                        }
                                    } else {
                                        $scope.find('.tx-ajax-search-pagination').css('display', 'none');
                                    }
                                }, 100);
                                prevData = data;
                            } else {
                                if ( data != prevData ) {
                                    prevData = data;
                                    if (data.includes('tx-no-results')) {
                                        $scope.find('.tx-ajax-search-pagination').css('display', 'none');
                                        $scope.find('.tx-search-plus-data-fetch ul').html('');
                                        $scope.closest('section').removeClass('tx-section-z-index');
                                    } else {
                                        $scope.find('.tx-ajax-search-pagination').css('display', 'flex');
                                    }

                                    $scope.find('.tx-search-plus-data-fetch ul').append( data );

                                    if (data == '') {
                                        $scope.find('.tx-load-more-results').fadeOut(100);
                                        setTimeout(function() {
                                            $scope.find( '.tx-pagination-loading' ).hide();
                                            $scope.find('.tx-no-more-results').fadeIn(100);
                                        }, 100);
                                    } else {
                                        $scope.find( '.tx-pagination-loading' ).hide();
                                        $scope.find('.tx-load-more-results').show();
                                    }

                                    if ($scope.find('.tx-search-plus-data-fetch ul').find('li').length < $scope.find('.tx-search-form-input').attr('number-of-results')) {
                                        $scope.find('.tx-load-more-results').fadeOut(100);
                                        setTimeout(function() {
                                            $scope.find( '.tx-pagination-loading' ).hide();
                                            $scope.find('.tx-no-more-results').fadeIn(100);
                                        }, 100);
                                    } else {
                                        $scope.find('.tx-load-more-results').show();
                                    }

                                    if ( $scope.find('.tx-search-plus-data-fetch ul').find('li').length == $scope.find('.tx-search-plus-data-fetch ul').find('li').data('number-of-results') ) {
                                        $scope.find('.tx-load-more-results').fadeOut(100);
                                        setTimeout(function() {
                                            $scope.find( '.tx-pagination-loading' ).hide();
                                            $scope.find('.tx-no-more-results').fadeIn(100);
                                        }, 100);
                                    } else {
                                        $scope.find('.tx-load-more-results').show();
                                    }
                                }
                            }

                            if (data.includes('tx-no-results')) {
                                $scope.find('.tx-ajax-search-pagination').css('display', 'none');
                                $scope.find('.tx-load-more-results').fadeOut();
                            } else {
                                $scope.find('.tx-ajax-search-pagination').css('display', 'flex');
                            }
                            
                            if (thisValue.length > 2) {
                                $scope.find('.tx-search-plus-data-fetch').slideDown(200);
                                $scope.find('.tx-search-plus-data-fetch ul').fadeTo(200, 1);
                            } else {
                                $scope.find('.tx-search-plus-data-fetch').slideUp(200);
                                $scope.find('.tx-search-plus-data-fetch ul').fadeTo(200, 0);
                                setTimeout(function() {
                                    $scope.find('.tx-search-plus-data-fetch ul').html('');
                                    $scope.find('.tx-no-results').remove();
                                    $scope.closest('section').removeClass('tx-section-z-index');
                                }, 600);
                                postsOffset = 0;
                            }
                        },
                        error: function(error) {
                            console.log(error);
                        }
                    });
                }, 400);
            }

            if ($scope.find('.tx-search-form-input').attr('ajax-search') === 'yes') {

                $scope.find('.tx-search-form').attr('autocomplete', 'off');
                
                var postsOffset = 0;

                $scope.find('.tx-load-more-results').on('click', function(e) {
                    postsOffset += +$scope.find('.tx-search-form-input').attr('number-of-results');
                    $scope.find('.tx-load-more-results').hide();
                    $scope.find( '.tx-pagination-loading' ).css( 'display', 'inline-block' );
                    ajaxSearchCall($scope.find('.tx-search-form-input'), postsOffset, e);
                });

                $scope.find('.tx-search-form-input').on('keyup', function(e) {
                    postsOffset = 0;
                    $scope.find('.tx-search-plus-data-fetch').hide();
                    $scope.find('.tx-search-plus-data-fetch ul').html('');
                    ajaxSearchCall($(this), postsOffset, e);
                });
    
                $scope.find('.tx-search-plus-data-fetch').on('click', '.tx-search-plus-close', function() {
                    $scope.find('.tx-search-form-input').val('');
                    $scope.find('.tx-search-plus-data-fetch').slideUp(200);
                    setTimeout(function() {
                        $scope.find('.tx-search-plus-data-fetch ul').html('');
                        $scope.find('.tx-no-results').remove();
                        $scope.closest('section').removeClass('tx-section-z-index');
                    }, 400);
                    postsOffset = 0;
                });

                $('body').on('click', function(e) {
                    if ( !e.target.classList.value.includes('tx-search-plus-data-fetch') && !e.target.closest('.tx-search-plus-data-fetch') ) {
                        if ( !e.target.classList.value.includes('tx-search-form') && !e.target.closest('.tx-search-form') ) {
                            $scope.find('.tx-search-form-input').val('');
                            $scope.find('.tx-search-plus-data-fetch').slideUp(200);
                            setTimeout(function() {
                                $scope.find('.tx-search-plus-data-fetch ul').html('');
                                $scope.find('.tx-no-results').remove();
                                $scope.closest('section').removeClass('tx-section-z-index');
                            }, 400);
                            postsOffset = 0;
                        }
                    }
                });

                var mutationObserver = new MutationObserver(function(mutations) {
                    $scope.find('.tx-search-plus-data-fetch li').on('click', function() {
                        var itemUrl = $(this).find('a').attr('href');
                        var itemUrlTarget = $(this).find('a').attr('target');
                        window.open(itemUrl, itemUrlTarget).focus();
                    });
                });

                // Listen to Mini Cart Changes
                mutationObserver.observe($scope[0], {
                    childList: true,
                    subtree: true,
                });
            }

        };


    jQuery(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/avas-search-plus.default', widgetSearchPlus);
    });

}(jQuery, window.elementorFrontend));


