/**
 * Product Filter Widget JavaScript
 */
(function($) {
    'use strict';

    function initFilterWidget() {

        // Initialize price slider
    if ($('.price-slider').length && typeof $.fn.slider !== 'undefined') {
        $('.price-slider').each(function() {
            var $slider = $(this);
            var min = parseInt($slider.data('min'));
            var max = parseInt($slider.data('max'));

            $slider.slider({
                range: true,
                min: min,
                max: max,
                values: [min, max],
                slide: function(event, ui) {
                    var $container = $(this).closest('.price-group');
                    $container.find('.price-min').text('$' + ui.values[0]);
                    $container.find('.price-max').text('$' + ui.values[1]);
                    $container.find('input[name="min_price"]').val(ui.values[0]);
                    $container.find('input[name="max_price"]').val(ui.values[1]);
                }
            });
        });
    }

    // Initialize attribute range sliders (for number-type attributes)
    if ($('.attribute-slider').length && typeof $.fn.slider !== 'undefined') {
        $('.attribute-slider').each(function() {
            var $slider = $(this);
            var attrId = $slider.data('attribute-id');
            var min = parseFloat($slider.data('min'));
            var max = parseFloat($slider.data('max'));
            var step = $slider.data('step') || 1;

            // Handle decimal steps
            if (step < 1) {
                step = parseFloat(step);
            }

            $slider.slider({
                range: true,
                min: min,
                max: max,
                step: step,
                values: [min, max],
                slide: function(event, ui) {
                    var $container = $(this).closest('.attribute-filter-group');
                    var unit = $container.find('.attribute-unit').first().text() || '';
                    $container.find('.attr-range-min').text(ui.values[0] + (unit ? ' ' + unit : ''));
                    $container.find('.attr-range-max').text(ui.values[1] + (unit ? ' ' + unit : ''));
                    $container.find('input[name="attr_' + attrId + '_min"]').val(ui.values[0]);
                    $container.find('input[name="attr_' + attrId + '_max"]').val(ui.values[1]);
                }
            });
        });
    }

    // Find all product containers on the page (supports multiple layouts)
    function findProductContainers() {
        var containers = [];

        // Standard product grid
        if ($('.ggmc-products-grid').length) {
            containers.push({
                element: $('.ggmc-products-grid'),
                items: $('.ggmc-products-grid .product-grid-item, .ggmc-products-grid .product-item'),
                type: 'grid'
            });
        }

        // Product list layout
        if ($('.ggmc-products-list').length) {
            containers.push({
                element: $('.ggmc-products-list'),
                items: $('.ggmc-products-list .product-list-item, .ggmc-products-list .product-item'),
                type: 'list'
            });
        }

        // Loop layouts
        if ($('.elementor-loop-container').length) {
            containers.push({
                element: $('.elementor-loop-container'),
                items: $('.elementor-loop-container .elementor-loop-item'),
                type: 'loop'
            });
        }

        // Custom product containers
        if ($('.products').length) {
            containers.push({
                element: $('.products'),
                items: $('.products .product, .products .product-item'),
                type: 'woocommerce'
            });
        }

        // Generic product containers
        if ($('[class*="product"]').length && containers.length === 0) {
            containers.push({
                element: $('[class*="product"]').first().parent(),
                items: $('[data-product-id], [data-id]').filter(function() {
                    return $(this).closest('.ggmc-product-filter').length === 0;
                }),
                type: 'generic'
            });
        }

        return containers;
    }

    // Handle form submission
    $('.filter-form').on('submit', function(e) {
        e.preventDefault();

        var formData = $(this).serialize();
        var $container = $(this).closest('.ggmc-product-filter');

        // Add loading state
        $container.addClass('loading');

        // Find product containers
        var productContainers = findProductContainers();

        if (productContainers.length === 0) {
            $container.removeClass('loading');
            return;
        }

        // Check if ggm_commerce_ajax is defined
        if (typeof ggm_commerce_ajax === 'undefined') {
            $container.removeClass('loading');
            // Can't use i18n here since ggm_commerce_ajax is undefined
            alert('Configuration error. Please refresh the page.');
            return;
        }


        // Collect product IDs present in the DOM so the server can scope
        // its query to only products on this page (e.g. category pages).
        var domProductIds = [];
        productContainers.forEach(function(pc) {
            pc.items.each(function() {
                var id = $(this).data('product-id');
                if (id) {
                    domProductIds.push(id);
                }
            });
        });

        // AJAX request to filter products
        $.ajax({
            url: ggm_commerce_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggm_commerce_filter_products',
                nonce: ggm_commerce_ajax.nonce,
                filter_data: formData,
                scope_product_ids: domProductIds.join(',')
            },
            success: function(response) {

                if (response.success) {
                    var filteredIds = response.data.product_ids;
                    var message = response.data.message;


                    // Update category and tag dropdowns to hide empty options
                    if (response.data.category_counts) {
                        var $categorySelect = $container.find('select[name="category"]');
                        $categorySelect.find('option').each(function() {
                            var $option = $(this);
                            var catId = parseInt($option.val());
                            if (catId > 0) {
                                var count = response.data.category_counts[catId] || 0;
                                if (count === 0) {
                                    $option.hide();
                                } else {
                                    $option.show();
                                }
                            }
                        });
                    }

                    if (response.data.tag_counts) {
                        var $tagSelect = $container.find('select[name="tags"]');
                        $tagSelect.find('option').each(function() {
                            var $option = $(this);
                            var tagId = parseInt($option.val());
                            if (tagId > 0) {
                                var count = response.data.tag_counts[tagId] || 0;
                                if (count === 0) {
                                    $option.hide();
                                } else {
                                    $option.show();
                                }
                            }
                        });
                    }

                    // Update attribute filter counts
                    if (response.data.attribute_counts) {
                        var hideEmpty = $container.data('hide-empty-attributes') === 'yes';

                        $.each(response.data.attribute_counts, function(attrId, valueCounts) {
                            var $filterGroup = $container.find('.attribute-filter-group[data-attribute-id="' + attrId + '"]');
                            var groupHasVisible = false;

                            // Check if the user has an active selection in this group
                            var hasActiveSelection = false;
                            var $checkedBoxes = $filterGroup.find('input[type="checkbox"]:checked');
                            var $selectedDropdown = $filterGroup.find('select.attribute-dropdown, select.attribute-select');
                            if ($checkedBoxes.length > 0) {
                                hasActiveSelection = true;
                            }
                            if ($selectedDropdown.length > 0 && $selectedDropdown.val()) {
                                hasActiveSelection = true;
                            }

                            // Update checkbox counts
                            $filterGroup.find('.attribute-checkbox-item, .checkbox-label').each(function() {
                                var $item = $(this);
                                var $input = $item.find('input') || $item.find('input[type="checkbox"]');
                                var value = $input.val();
                                var count = valueCounts[value] || 0;
                                var $countSpan = $item.find('.attribute-count, .count');

                                if ($countSpan.length) {
                                    $countSpan.text('(' + count + ')');
                                }

                                if (count === 0 && !$input.is(':checked')) {
                                    $item.addClass('no-results');
                                    if (hideEmpty) {
                                        $item.hide();
                                    }
                                } else {
                                    $item.removeClass('no-results');
                                    $item.show();
                                    groupHasVisible = true;
                                }
                            });

                            // Update dropdown counts
                            $filterGroup.find('select.attribute-dropdown option, select.attribute-select option').each(function() {
                                var $option = $(this);
                                var value = $option.val();
                                if (value) {
                                    var count = valueCounts[value] || 0;
                                    var text = $option.data('original-text') || $option.text().replace(/\s*\(\d+\)$/, '');
                                    $option.data('original-text', text);
                                    $option.text(text + ' (' + count + ')');

                                    // Don't hide the currently selected option
                                    var isSelected = $option.parent('select').val() === value;
                                    if (count === 0 && !isSelected) {
                                        if (hideEmpty) {
                                            $option.hide();
                                        }
                                    } else {
                                        $option.show();
                                        groupHasVisible = true;
                                    }
                                } else {
                                    // "All" option is always visible
                                    groupHasVisible = true;
                                }
                            });

                            // Never hide a group the user is actively filtering by
                            if (hasActiveSelection) {
                                groupHasVisible = true;
                            }

                            // Hide entire attribute group if all values are empty
                            if (hideEmpty && !groupHasVisible) {
                                $filterGroup.hide();
                            } else {
                                $filterGroup.show();
                            }
                        });

                        // Hide attribute groups that weren't in the response at all
                        // (no filtered products have values for those attributes)
                        if (hideEmpty) {
                            $container.find('.attribute-filter-group').each(function() {
                                var $group = $(this);
                                var groupAttrId = String($group.data('attribute-id'));
                                if (!response.data.attribute_counts[groupAttrId]) {
                                    // Check if user has an active selection in this group
                                    var hasSelection = $group.find('input[type="checkbox"]:checked').length > 0;
                                    var $select = $group.find('select.attribute-dropdown, select.attribute-select');
                                    if ($select.length > 0 && $select.val()) {
                                        hasSelection = true;
                                    }
                                    if (!hasSelection) {
                                        $group.hide();
                                    }
                                }
                            });
                        }
                    }

                    // Update price slider range to reflect filtered products
                    if (response.data.price_range) {
                        var newMin = Math.floor(response.data.price_range.min);
                        var newMax = Math.ceil(response.data.price_range.max);
                        $container.find('.price-slider').each(function() {
                            var $slider = $(this);
                            if ($slider.hasClass('ui-slider')) {
                                var currentVals = $slider.slider('values');
                                // Update the slider bounds
                                $slider.slider('option', 'min', newMin);
                                $slider.slider('option', 'max', newMax);
                                // Clamp current values to new bounds
                                var clampedMin = Math.max(currentVals[0], newMin);
                                var clampedMax = Math.min(currentVals[1], newMax);
                                $slider.slider('values', [clampedMin, clampedMax]);
                                // Update display labels
                                var $priceGroup = $slider.closest('.price-group');
                                var currency = ($priceGroup.find('.price-min').text().match(/^[^\d]*/) || ['$'])[0];
                                $priceGroup.find('.price-min').text(currency + clampedMin);
                                $priceGroup.find('.price-max').text(currency + clampedMax);
                                $priceGroup.find('input[name="min_price"]').val(clampedMin);
                                $priceGroup.find('input[name="max_price"]').val(clampedMax);
                            }
                        });
                        // Update min/max inputs if using input mode
                        $container.find('.price-inputs').each(function() {
                            $(this).find('input[name="min_price"]').attr('min', newMin).attr('placeholder', newMin);
                            $(this).find('input[name="max_price"]').attr('max', newMax).attr('placeholder', newMax);
                        });
                    }

                    // Trigger custom event for product grid to handle display
                    // Product grid script will handle showing/hiding products
                    $(document).trigger('ggm_commerce_products_filtered', [response.data]);

                    // Reset sorting controls to default when filters are applied
                    $('.table-sort-select, .grid-sort-select').val('');

                    // Update URL with filter parameters (optional)
                    if (window.history && window.history.replaceState) {
                        var url = new URL(window.location);
                        if (formData) {
                            url.searchParams.set('filter', btoa(formData));
                        } else {
                            url.searchParams.delete('filter');
                        }
                        window.history.replaceState({}, '', url);
                    }
                }

                $container.removeClass('loading');
            },
            error: function() {
                $container.removeClass('loading');
                var errorMsg = (ggm_commerce_ajax.i18n && ggm_commerce_ajax.i18n.filter_error)
                    ? ggm_commerce_ajax.i18n.filter_error
                    : 'Error filtering products. Please try again.';
                alert(errorMsg);
            }
        });
    });

    // Handle reset
    $('.filter-reset-btn').on('click', function(e) {
        e.preventDefault();

        var $form = $(this).closest('.filter-form');
        $form[0].reset();

        // Reset price slider (restore original bounds and values)
        $('.price-slider').each(function() {
            var $slider = $(this);
            var min = parseInt($slider.data('min'));
            var max = parseInt($slider.data('max'));

            if ($slider.hasClass('ui-slider')) {
                $slider.slider('option', 'min', min);
                $slider.slider('option', 'max', max);
                $slider.slider('values', [min, max]);
                var $priceGroup = $slider.closest('.price-group');
                var currency = ($priceGroup.find('.price-min').text().match(/^[^\d]*/) || ['$'])[0];
                $priceGroup.find('.price-min').text(currency + min);
                $priceGroup.find('.price-max').text(currency + max);
                $priceGroup.find('input[name="min_price"]').val(min);
                $priceGroup.find('input[name="max_price"]').val(max);
            }
        });

        // Reset price inputs (min/max mode)
        $form.find('.price-inputs').each(function() {
            var $minInput = $(this).find('input[name="min_price"]');
            var $maxInput = $(this).find('input[name="max_price"]');
            $minInput.val('');
            $maxInput.val('');
        });

        // Reset attribute sliders
        $('.attribute-slider').each(function() {
            var $slider = $(this);
            var attrId = $slider.data('attribute-id');
            var min = parseFloat($slider.data('min'));
            var max = parseFloat($slider.data('max'));

            if ($slider.hasClass('ui-slider')) {
                $slider.slider('values', [min, max]);
                var $container = $slider.closest('.attribute-filter-group');
                var unit = $container.find('.attribute-unit').first().text() || '';
                $container.find('.attr-range-min').text(min + (unit ? ' ' + unit : ''));
                $container.find('.attr-range-max').text(max + (unit ? ' ' + unit : ''));
                $container.find('input[name="attr_' + attrId + '_min"]').val(min);
                $container.find('input[name="attr_' + attrId + '_max"]').val(max);
            }
        });

        // Reset attribute number inputs
        $form.find('.attribute-inputs').each(function() {
            var $container = $(this).closest('.attribute-filter-group');
            var attrId = $container.data('attribute-id');
            var $minInput = $(this).find('input[name="attr_' + attrId + '_min"]');
            var $maxInput = $(this).find('input[name="attr_' + attrId + '_max"]');
            $minInput.val($minInput.data('min') || '');
            $maxInput.val($maxInput.data('max') || '');
        });

        // Reset attribute text search inputs
        $form.find('.attribute-text-search').val('');

        // Reset attribute checkboxes and dropdowns
        $form.find('.attribute-checkbox-item input').prop('checked', false);
        $form.find('.attribute-dropdown').val('');

        // Remove no-results class and show all options, groups, and items
        $form.find('.attribute-checkbox-item').removeClass('no-results').show();
        $form.find('.attribute-filter-group').show();
        $form.find('.attribute-dropdown option').show();

        // Show all category and tag options
        $form.find('select[name="category"] option, select[name="tags"] option').show();

        // Product grid script will handle showing all products via its own reset handler
        // Don't manipulate products here to avoid conflicts

        // Clear URL parameters
        if (window.history && window.history.replaceState) {
            var url = new URL(window.location);
            url.searchParams.delete('filter');
            window.history.replaceState({}, '', url);
        }
    });

    // Apply filters from URL on page load
    $(window).on('load', function() {
        var url = new URL(window.location);
        var filterData = url.searchParams.get('filter');
        if (filterData) {
            try {
                var decodedData = atob(filterData);
                var params = new URLSearchParams(decodedData);

                // Populate form fields
                params.forEach(function(value, key) {
                    var $field = $('[name="' + key + '"]');
                    if ($field.length) {
                        if ($field.is(':checkbox')) {
                            // Handle checkbox arrays for attribute filters
                            $field.filter('[value="' + value + '"]').prop('checked', true);
                        } else {
                            $field.val(value);
                        }
                    }
                });

                // Update attribute slider displays if values were restored
                $('.attribute-slider').each(function() {
                    var $slider = $(this);
                    var attrId = $slider.data('attribute-id');
                    var $container = $slider.closest('.attribute-filter-group');
                    var minVal = $container.find('input[name="attr_' + attrId + '_min"]').val();
                    var maxVal = $container.find('input[name="attr_' + attrId + '_max"]').val();

                    if (minVal && maxVal && $slider.hasClass('ui-slider')) {
                        $slider.slider('values', [parseFloat(minVal), parseFloat(maxVal)]);
                        var unit = $container.find('.attribute-unit').first().text() || '';
                        $container.find('.attr-range-min').text(minVal + (unit ? ' ' + unit : ''));
                        $container.find('.attr-range-max').text(maxVal + (unit ? ' ' + unit : ''));
                    }
                });

                // Trigger filter
                $('.filter-form').trigger('submit');
            } catch (e) {
            }
        }
    });
    }

    // Initialize on DOM ready
    $(document).ready(function() {
        initFilterWidget();
    });

    // Also initialize when Elementor frontend loads
    $(window).on('elementor/frontend/init', function() {
        initFilterWidget();
    });

    // Re-initialize after any AJAX page load
    $(document).on('elementor/popup/show', function() {
        setTimeout(initFilterWidget, 100);
    });

})(jQuery);
