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



    $('body').on('click', '.wpsis_title_container .wpsis_dropdown_content li:not(.disabled)', function(){



        var parent_li = $(this).parents('.wpsis:first');

        var parent_wrapper = $(this).parents('.wpsis_title_container:first');

        var loading_img = parent_wrapper.find('.wpsis_loading img');

        var parent_content = $(this).parents('ul.wpsis_dropdown_content:first');

        var this_type = parent_content.attr('data-type');

        var this_all = parent_content.find('li');

        var this_view = parent_wrapper.find('.wpsis_current[data-type="'+this_type+'"]');

        var this_key = $(this).attr('data-key');



        if(this_view.text().trim() == this_key){

            return;

        }



        this_view.html(this_key);

        this_all.removeClass('active');

        $(this).addClass('active');

        parent_content.hide();

        // loading_img.show();



        var current_state = parent_wrapper.find('.wpsis_current[data-type="states"]').text().trim();

        var current_year = parent_wrapper.find('.wpsis_current[data-type="years"]').text().trim();

        var li_type = parent_li.hasClass('wpsis_all') ? 'wpsis_all' : 'wpsis_quarterly';



        var current_url = new URL(window.location.href);



        current_url.searchParams.set('wpsis_state', current_state);

        current_url.searchParams.set('wpsis_year', current_year);

        current_url.searchParams.set('wpsis_type', li_type);



        loading_img.show();

        var ajax_data = {

            action: 'wpsis_get_update_order_states',

            wpsis_year: current_year, 

            wpsis_state: current_state, 

            wpsis_type: li_type, 

            wpsis_nonce: wpsis_obj.wpsis_nonce

        }





        $.post(ajaxurl, ajax_data, function(resp, code){

            

            loading_img.hide();

            

            if(code == 'success' && resp){

                parent_li.find('.woocommerce-summary__item-data').remove();

                parent_wrapper.after(resp);

            }        



        });



      





    });

    $('body').on('click', '.wpsis_title_container .wpsis_current', function(){

    

        var type = $(this).data('type');

        var parent_wrapper = $(this).parents('.wpsis_title_container:first');

        $('.wpsis_title_container .wpsis_current').attr('data-show', false);

    

        var all_content = $('ul.wpsis_dropdown_content');

        var dropdown_content_visible = parent_wrapper.find('ul.wpsis_dropdown_content[data-type="'+type+'"]:visible');

        var dropdown_content = parent_wrapper.find('ul.wpsis_dropdown_content[data-type="'+type+'"]');

        all_content.hide();



        if(dropdown_content_visible.length > 0){

        }else{

            $(this).attr('data-show', true);

            dropdown_content.show();

        }

    

    });

	
	$('body').on('click', '.wpsis-load-products-for-sitemap', function(){
		$.blockUI({ message: null });

		$.post(ajaxurl, {
			action: 'wpsis_load_products',
			nonce: wpsis_obj.wpsis_nonce
		}, function(res){
			$.unblockUI();

			$('#wpsis_products_list').html(res);
			
			$('#wpsis_days, #wpsis_analyze, label[for="wpsis_days"]').show();
		});
	});

	function sortRowsByPriority() {

		let $tbody = $('#wpsis_products_list tbody');
	
		let rows = $tbody.find('tr.wpsis_product_row').get();
	
		rows.sort(function(a, b) {
			let aVal = parseFloat($(a).find('.wpsis_priority').val()) || 0;
			let bVal = parseFloat($(b).find('.wpsis_priority').val()) || 0;
			return bVal - aVal; // highest first
		});
	
		// Smooth fade reposition
		$(rows).each(function(index, row) {
			$(row).css('opacity', 0.3);
			$tbody.append(row);
			$(row).animate({ opacity: 1 }, 200);
		});
	}
	$('body').on('input', '.wpsis_priority', function() {
		sortRowsByPriority();
	});

	let analyzing = false;
	
	$('body').on('click', '#wpsis_analyze', function(){
	
		if(analyzing) return;
		analyzing = true;
		
		$('#wpsis_days, #wpsis_analyze, #wpsis_generate').attr('disabled', true);
	
		let days = parseInt($('#wpsis_days').val());
	
		$('#wpsis_progress').html('Initializing...');
	
		function processBatch(reset = false){
	
			$.post(wpsis_obj.ajax_url, {
				action: 'wpsis_analyze_priority',
				days: days,
				nonce: wpsis_obj.wpsis_nonce,
				reset: reset ? 1 : 0
			}, function(res){
	
				if(res.done){
					$('#wpsis_progress').html(
						'Analysis complete!<br>' +
						'Total Orders: ' + res.progress.total
					);
					analyzing = false;
					$('#wpsis_days, #wpsis_analyze, #wpsis_generate').attr('disabled', false);
					$('#wpsis_generate').show();
					return;
				}
	
				// Update UI with accumulated values
				res.products.forEach(p => {
					$('#sales_' + p.product_id).text(p.sales);
					$('#priority_' + p.product_id).val(p.priority);
				});
				sortRowsByPriority();
	
				$('#wpsis_progress').html(
					'Batch processed: ' + res.batch_size + ' orders<br>' +
					'Processed: ' + res.progress.processed + ' / ' + res.progress.total + '<br>' +
					'Remaining: ' + res.progress.remaining
				);
	
				processBatch(false);
	
			}, 'json');
		}
	
		processBatch(true); // true = reset first run
	});

			
	$('#wpsis_generate').on('click', function() {
		let products = [];
	
		$('.wpsis_product_row').each(function() {
			const $row = $(this);
			if ($row.find('.wpsis_include').is(':checked')) {
				const id       = $row.data('id');
				const link     = $row.find('a').attr('href');
				const image    = $row.find('img').attr('src');
				const priority = parseFloat($row.find('.wpsis_priority').val()) || 0.5;
	
				products.push({
					id: id,
					loc: link,
					image: image,
					priority: priority
				});
			}
		});
	
		if (products.length === 0) {
			alert('Please select at least one product.');
			return;
		}
	
		$.blockUI({ 
			message: '<h2>Generating sitemap... Please wait</h2>',
			css: { 
				border: 'none', 
				padding: '15px', 
				backgroundColor: '#000', 
				color: '#fff', 
				borderRadius: '10px', 
				opacity: 0.8
			}
		});
	
		$.post(ajaxurl, {
			action: 'wpsis_generate_sitemap',
			nonce: wpsis_obj.wpsis_nonce,
			products: products
		}, function(res) {
			$.unblockUI();
			if (res.error) {
				alert(res.error);
				return;
			}
			$('#wpsis_sitemap_download').html(
				'<a href="' + res.url + '" target="_blank" class="button button-primary">Download Sitemap</a>'
			);
			if (res.warnings && res.warnings.length) {
				console.warn('Sitemap warnings:', res.warnings);
			}
		}, 'json').fail(function(xhr, status, error) {
			$.unblockUI();
			alert('AJAX request failed: ' + error);
			console.error(xhr.responseText);
		});
	});



	










});