/*
	** Category Ajax Js
	** Version: 1.0.0
*/
jQuery(document).ready(function($) {
	// Store active filters
	var activeFilters = {
		product_cat: [],
		attributes: {},
		min_price: null,
		max_price: null,
		orderby: $('.orderby').val() || 'menu_order',
		product_brand: [],
		paged: 1
	};
	
	function throttle(fn, wait) {
        var time = Date.now();
        return function() {
            if ((time + wait - Date.now()) < 0) {
                fn();
                time = Date.now();
            }
        };
    }
	
	var loading_template = $( '#swg-filter-ajax-loading' );

	// Active Filter
	function updateActiveFilters() {
		var $list = $('.active-filters-list');
		$list.empty();
		
		// Add categories
		activeFilters.product_cat.forEach(function(slug) {
			var term = $('.widget_product_categories a[data-slug="/' + slug + '/"]').text() || slug;
			$list.append(
				'<li>' + term + ' <a href="#" class="remove-filter" data-type="category" data-value="' + slug + '">×</a></li>'
			);
		});
		
		// Add categories brand
		activeFilters.product_brand.forEach(function(slug) {
			var brand_term = $('.sw_brand_filter a[data-slug="' + slug + '"]').text() || slug;
			$list.append(
				'<li>' + brand_term + ' <a href="#" class="remove-filter" data-type="brand" data-value="' + slug + '">×</a></li>'
			);
		});

		// Add price range
		if (activeFilters.min_price || activeFilters.max_price) {
			var priceText = '';
			if (activeFilters.min_price && activeFilters.max_price) {
				priceText = '$' + activeFilters.min_price + ' - $' + activeFilters.max_price;
			} else if (activeFilters.min_price) {
				priceText = 'From $' + activeFilters.min_price;
			} else {
				priceText = 'Up to $' + activeFilters.max_price;
			}
			$list.append(
				'<li>Price: ' + priceText + ' <a href="#" class="remove-filter" data-type="price">×</a></li>'
			);
		}

		// Add attributes
		for (var taxonomy in activeFilters.attributes) {
            activeFilters.attributes[taxonomy].forEach(function(slug) {
                var term = $('.widget_layered_nav a[data-taxonomy="' + taxonomy + '"][data-slug="' + slug + '"]').text() || slug;
                var label = taxonomy.replace('pa_', '').replace('-', ' ').replace(/\b\w/g, l => l.toUpperCase());
                $list.append(
                    '<li>' + term + ' <a href="#" class="remove-filter" data-type="attribute" data-taxonomy="' + taxonomy + '" data-value="' + slug + '">×</a></li>'
                );
            });
        }

		// Add sorting
		if (activeFilters.orderby !== 'menu_order') {
			var sortLabel = activeFilters.orderby;
			$list.append(
				'<li>' + sortLabel + ' <a href="#" class="remove-filter" data-type="orderby">×</a></li>'
			);
		}

		// Show/hide clear all button
		if ($list.children().length > 0) {
			$('.widget_woo_active_filters').show();
			
		} else {
			$('.widget_woo_active_filters').hide();
		}
	}

	// Handle price filter
	$('.widget_price_filter form').on('submit', function(e) {
		e.preventDefault();
		activeFilters.min_price = $('.widget_price_filter input[name="min_price"]').val();
		activeFilters.max_price = $('.widget_price_filter input[name="max_price"]').val();
		isLoadMore = false;
		wcAjaxFilterProducts();
	});

	// Handle category filter
	$('.widget_product_categories a').on('click', function(e) {
		e.preventDefault();
		var slug = $(this).data('slug');
		slug = slug.replaceAll( '/', '' );
		if (slug) {
			var index = activeFilters.product_cat.indexOf(slug);
			if (index === -1) {
				activeFilters.product_cat.push(slug);
				$(this).parent().addClass('active current-cat');
			} else {
				activeFilters.product_cat.splice(index, 1);
				$(this).parent().removeClass('active current-cat');
			}
			isLoadMore = false;
			activeFilters.paged = 1; // Reset to page 1 on filter change
			wcAjaxFilterProducts();
		}
	});
	
	// Handle category brand filter
	$('.sw_brand_filter a').on('click', function(e) {
		e.preventDefault();
		var slug = $(this).data('slug');
		if (slug) {
			var index = activeFilters.product_brand.indexOf(slug);
			if (index === -1) {
				activeFilters.product_brand.push(slug);
				$(this).parent().addClass('active');
			} else {
				activeFilters.product_brand.splice(index, 1);
				$(this).parent().removeClass('active');
			}
			isLoadMore = false;
			activeFilters.paged = 1; // Reset to page 1 on filter change
			wcAjaxFilterProducts();
		}
	});

	// Handle layered nav (attributes) filter
	$('.widget_layered_nav a').on('click', function(e) {
        e.preventDefault();
        var taxonomy = $(this).data('taxonomy');
        var value = $(this).data('slug');
        if (taxonomy && value) {
            // Initialize taxonomy array if it doesn't exist
            if (!activeFilters.attributes[taxonomy]) {
                activeFilters.attributes[taxonomy] = [];
            }

            // Toggle attribute value
            var index = activeFilters.attributes[taxonomy].indexOf(value);
			
            if (index === -1) {
                activeFilters.attributes[taxonomy].push(value);

                $(this).parent().addClass('chosen');
            } else {
                activeFilters.attributes[taxonomy].splice(index, 1);
                $(this).parent().removeClass('chosen');
                // Remove taxonomy if no values remain
                if (activeFilters.attributes[taxonomy].length === 0) {
                    delete activeFilters.attributes[taxonomy];
                }
            }
            activeFilters.paged = 1;
            isLoadMore = false;
            wcAjaxFilterProducts();
        }
    });

	// Handle ordering dropdown
	$('.orderby').on('change', function(e) {
		e.preventDefault();
		activeFilters.orderby = $(this).val();
		activeFilters.paged = 1;
		isLoadMore = false;
		wcAjaxFilterProducts();
	});
	
	//handle ordering custom
	$( '.woocommerce-ordering ul > li' ).on( 'click', function(){
		activeFilters.orderby = $(this).attr( 'data-value' );
		activeFilters.paged = 1;
		isLoadMore = false;
		wcAjaxFilterProducts();
	});
	// Prevent default form submission for ordering
	$('.woocommerce-ordering').on('submit', function(e) {
		e.preventDefault();
	});
	
	// pagination ajax
	$(document).on('click', '.woocommerce-pagination a.page-numbers', function(e) {
		e.preventDefault();
		var href = $(this).attr('href');
		var paged = 1;

		if (href.includes('paged=')) {
			paged = parseInt(href.match(/paged=(\d+)/)[1]) || 1;
		} else if (href.includes('page/')) {
			paged = parseInt(href.match(/page\/(\d+)/)[1]) || 1;
		} else {
			// Handle relative page numbers (e.g., Next/Prev)
			var currentPage = activeFilters.paged;
			if ($(this).hasClass('next')) {
				paged = currentPage + 1;
			} else if ($(this).hasClass('prev')) {
				paged = Math.max(1, currentPage - 1);
			} else {
				// Extract from text or fallback
				paged = parseInt($(this).text()) || 1;
			}
		}
		activeFilters.paged = paged;
		isLoadMore = false;
		wcAjaxFilterProducts();
	});

	// pagination ajax
	$(document).on('click', '.pagination-ajax > button', function(e) {
		e.preventDefault();
		activeFilters.paged++;		
		var maxpage = $(this).data( 'maxpage' );		
		if( maxpage >= activeFilters.paged ){	
			$(this).addClass( 'loading' );
			isLoadMore = true;
			wcAjaxFilterProducts();			
		}
	});
	
	$(window).on('scroll', throttle(function() {	
		if( swg_filter.loadmore_style == 0 ){
			return;
		}
		var productsBottom = $('.products').offset().top + $('.products').outerHeight();
		var windowBottom = $(window).scrollTop() + $(window).height();
		var buffer = 100; // Trigger 100px before reaching the bottom
		var maxpage = $( '.pagination-ajax > button' ).data( 'maxpage' );
		if (windowBottom + buffer > productsBottom && maxpage > activeFilters.paged ) {
			$( '.pagination-ajax > button' ).addClass( 'loading' );
			activeFilters.paged++;
			isLoadMore = true;
			wcAjaxFilterProducts();
		}
	}, 500)); // Throttle to check every 500ms
	
	//Remove Filter
	$(document).on('click', '.remove-filter', function(e) {
		e.preventDefault();
		var type = $(this).data('type');
		var value = $(this).data('value');
		var taxonomy = $(this).data('taxonomy');

		if (type === 'category') {
			var index = activeFilters.product_cat.indexOf(value);
			if (index !== -1) {
				activeFilters.product_cat.splice(index, 1);
				$('.widget_product_categories a[data-slug="/' + value + '/"]').parent().removeClass('active current-cat');
			}
		} 
		else if (type === 'attribute' && taxonomy) {
			var index = activeFilters.attributes[taxonomy] ? activeFilters.attributes[taxonomy].indexOf(value) : -1;
            if (index !== -1) {
                activeFilters.attributes[taxonomy].splice(index, 1);
                $('.widget_layered_nav a[data-taxonomy="' + taxonomy + '"][data-slug="' + value + '"]').parent().removeClass('chosen');
                if (activeFilters.attributes[taxonomy].length === 0) {
                    delete activeFilters.attributes[taxonomy];
                }
            }			
		} 
		else if (type === 'price') {
			activeFilters.min_price = null;
			activeFilters.max_price = null;
			$('.wc-price-filter input[name="min_price"]').val('');
			$('.wc-price-filter input[name="max_price"]').val('');
		} 
		else if (type === 'orderby') {
			activeFilters.orderby = 'menu_order';
			$('.orderby').val('menu_order');
		}
		else if (type === 'brand') {
			var index = activeFilters.product_brand.indexOf(value);
			if (index !== -1) {
				activeFilters.product_brand.splice(index, 1);
				$('.sw_brand_filter a[data-slug="' + value + '"]').parent().removeClass('active');
			}
		}

		activeFilters.paged = 1;
		isLoadMore = false;
		wcAjaxFilterProducts();
	});
	
	//Clear all filter
	$('.clear-all-filters').on('click', function(e) {
		e.preventDefault();
		activeFilters = {
			product_cat: [],
			product_brand: [],
			attributes: {},
			min_price: null,
			max_price: null,
			orderby: 'menu_order',
			paged: 1
		};
		$('.widget_product_categories li').removeClass('active current-cat');
		$('.widget_layered_nav li').removeClass('chosen');
		$('.sw_brand_filter li').removeClass('active');
		$('.wc-price-filter input[name="min_price"]').val('');
		$('.wc-price-filter input[name="max_price"]').val('');
		$('.orderby').val('menu_order');
		isLoadMore = false;
		wcAjaxFilterProducts();
	});
	
	// Function to perform AJAX filtering
	function wcAjaxFilterProducts() {
		var data = {
			action: 'wc_ajax_filter',
			dataType: 'json',
			product_cat: activeFilters.product_cat,
			product_brand: activeFilters.product_brand,
			min_price: activeFilters.min_price,
			max_price: activeFilters.max_price,
			attributes: activeFilters.attributes,
			orderby: activeFilters.orderby,
			paged: activeFilters.paged
		};

		$.ajax({
			url: custom_text.ajax_url,
			type: 'POST',
			data: data,
			beforeSend: function() {
				$('body').append( loading_template.html() );
			},
			success: function(response) { 
				if (response.success) {
					// Update product loop
					if (isLoadMore) {
						$('.products').append(response.data.html);
					} else {
						$('.products').html(response.data.html);
					}
					if( $('.woocommerce-pagination').length > 0 ){
						$('.woocommerce-pagination').html(response.data.pagination);
					}else{
						$(response.data.pagination).insertAfter( $('.products') );
					}
					$('.woocommerce-result-count').html(response.data.result_count);
					updateActiveFilters();
					// Update URL with current parameters
					var params = new URLSearchParams();
					if (activeFilters.product_cat.length) {
						params.set('product_cat', activeFilters.product_cat.join(','));
					}
					if (activeFilters.min_price) {
						params.set('min_price', activeFilters.min_price);
					}
					if (activeFilters.max_price) {
						params.set('max_price', activeFilters.max_price);
					}
					if (activeFilters.orderby) {						
						params.set('orderby', activeFilters.orderby);
					}
					for (var taxonomy in activeFilters.attributes) {
                        if (activeFilters.attributes[taxonomy].length) {
                            params.set(taxonomy, activeFilters.attributes[taxonomy].join(','));
                        }
                    }
					if (activeFilters.product_brand.length) {
						params.set('product_brand', activeFilters.product_brand.join(','));
					}
					if (activeFilters.paged > 1) {
						params.set('paged', activeFilters.paged);
					}
					var newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
					history.pushState({}, '', newUrl);
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				
			},
			complete: function() {
				$('.pagination-ajax > button').removeClass('loading');			
				if (!isLoadMore) {
					$('html,body').animate({
						scrollTop: ( $("ul.products").offset().top -115 )},
					300);
				}
				$('.product-loader').remove();
			}
		});
	}

	// Initialize filters from URL on page load
	function initFiltersFromUrl() { 
		var params = new URLSearchParams(window.location.search);
		activeFilters.product_cat = params.get('product_cat') ? params.get('product_cat').split(',') : [];
		if( swg_filter.is_category == 1 ){
			activeFilters.product_cat = swg_filter.current_cat.split(',');
		}
		activeFilters.min_price = params.get('min_price') || null;
		activeFilters.max_price = params.get('max_price') || null;
		activeFilters.orderby = params.get('orderby') || $('.orderby').val() || 'menu_order';
		activeFilters.product_brand = params.get('product_brand') ? params.get('product_brand').split(',') : [];
		if( swg_filter.is_brand == 1 ){
			activeFilters.product_brand = swg_filter.current_brand.split(',');
		}
		
		activeFilters.attributes = {};
        params.forEach(function(value, key) {
            if (key.startsWith('pa_')) {
                activeFilters.attributes[key] = value.split(',').filter(slug => slug);
                // Highlight active attributes
                activeFilters.attributes[key].forEach(function(slug) {
                    $('.widget_layered_nav a[data-taxonomy="' + key + '"][data-slug="' + slug + '"]').parent().addClass('chosen');
                });
            }
        });

		// Highlight active categories
		$('.widget_product_categories a').each(function() {
			var slug = $(this).data('slug');
			slug = slug.replaceAll( '/', '' );
			if (activeFilters.product_cat.includes(slug)) {
				$(this).parent().addClass('current-cat');
			}
		});
		
		// Highlight active brand
		$('.sw_brand_filter a').each(function() {
			var slug = $(this).data('slug');
			if (activeFilters.product_brand.includes(slug)) {
				$(this).parent().addClass('active');
			}
		});
		
		$('.orderby').val(activeFilters.orderby);
		
		updateActiveFilters();

		// Trigger initial AJAX if filters exist
		if (params.toString()) {
			isLoadMore = activeFilters.paged > 1;
			wcAjaxFilterProducts();
		}
	}

	// Run initialization
	initFiltersFromUrl();

	// Handle popstate for back/forward navigation
	$(window).on('popstate', function() {
		initFiltersFromUrl();
	});
});