(function ($) {
    const $root = $('#sapsfwc-root');
    if (!$root.length) return;

    const toBool = v => String(v) === '1';

    const toggleSel = 'a[href$="#sapsfwc-toggle"], a[href*="#sapsfwc-toggle"], .sapsfwc-toggle';

    const cfg = {
        ajaxUrl: $root.data('ajaxUrl') || '',
        nonce: $root.data('nonce') || '',
        shopUrl: $root.data('shopUrl') || '',
        loadMoreEnabled: toBool($root.data('loadMoreEnabled')),
        closeButtonTransform: toBool($root.data('closeButtonTransform'))
    };

    let ajaxInProgress = false;
    const $productsArchive = $('.sapsfwc-archive').first();
    const body = $('body');
    const ajaxSearchWrap = $('.sapsfwc-wrap');
    const viewAllWrap = $('.sapsfwc-view-all-results');
    const viewAllLink = $('.sapsfwc-view-all-results a');
    const baseShopURL = cfg.shopUrl;

    

    let currentPage = 1;
    let totalPages = 1;
    const typingDelay = 500;
    let typingTimer;

    const getProducts = function (append = false) {
        if (ajaxInProgress) return;
        ajaxInProgress = true;

        $('.sapsfwc-loader, .sapsfwc-load-more-loader').remove();

        const $loader = $('<div class="sapsfwc-loader"><div></div></div>');

        if (!append) {
            $productsArchive.after($loader);
        } else {
            $('.sapsfwc-load-more-wrap').append('<div class="sapsfwc-load-more-loader sapsfwc-loader"></div>');
        }

        $.ajax({
            url: cfg.ajaxUrl,
            type: 'post',
            data: {
                action: 'sapsfwc_products',
                current_page: currentPage,
                search: $productsArchive.data('search') || '',
                security: cfg.nonce
            },
            success: function (response) {
                try {
                    const content = (response && response.html ? String(response.html) : '').trim();

                    if (append) {
                        $('.sapsfwc-load-more-loader').remove();
                        $productsArchive.animate({scrollTop: $productsArchive[0].scrollHeight}, 400);
                        $productsArchive.append(content);
                    } else {
                        $productsArchive.html(content);
                        $loader.remove();
                    }

                    if (typeof response.total_pages !== 'undefined') {
                        totalPages = response.total_pages;
                    }

                    

                    ajaxInProgress = false;

                } catch (e) {
                    console.error('Invalid JSON response', e);
                    $loader.remove();
                    $('.sapsfwc-load-more-loader').remove();
                    ajaxInProgress = false;
                }
            },
            error: function () {
                $loader.remove();
                $('.sapsfwc-load-more-loader').remove();
                ajaxInProgress = false;
            }
        });
    };

    function addEvents() {

        $(document).on('click', toggleSel, function (e) {
            e.preventDefault();

            body.toggleClass('sapsfwc-open');
            ajaxSearchWrap.toggleClass('active');

            setTimeout(function () {
                $('.sapsfwc-form input').trigger('focus');
            }, 100);
        });

        $(document).on('keydown', toggleSel, function (e) {

            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                $(this).trigger('click');
            }

        });

        $(document).on('click', '.sapsfwc-close', function () {
            ajaxSearchWrap.removeClass('active');
            body.removeClass('sapsfwc-open');
        });

        $('.sapsfwc-form input').on('input', function () {
            clearTimeout(typingTimer);

            const $input = $(this);
            const searchTerm = $input.val().trim();

            if (searchTerm.length > 2) {

                typingTimer = setTimeout(function () {
                    $productsArchive.data('search', searchTerm);
                    currentPage = 1;
                    getProducts(false);

                    if (viewAllWrap.length && viewAllLink.length) {
                        viewAllLink.attr('href', baseShopURL + '?s=' + encodeURIComponent(searchTerm));
                        viewAllWrap.removeClass('is-hidden');
                    }
                }, typingDelay);

            } else {

                clearTimeout(typingTimer);
                $productsArchive.empty();

                

                if (viewAllWrap.length) {
                    viewAllWrap.addClass('is-hidden');
                }

            }
        });

        $(document).on('click', '.sapsfwc-form-submit', function () {
            $(this).closest('form').trigger('submit');
        });

        
    }

    $(addEvents);

})(jQuery);