/**
 * WooCommerce Product Data - Topping Sets functionality
 *
 * @package Foodord
 */

(function($) {
	'use strict';

	/**
	 * Product Data Topping Sets Manager
	 */
	const ProductDataToppingSets = {

		/**
		 * Initialize the module
		 */
		init: function() {
			this.bindEvents();
			this.setupDragDrop();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function() {
			// Toggle card selection on checkbox change
			$(document).on('change', '.foodord-topping-card__enable', this.handleToggle);

			// Expand/collapse category list
			$(document).on('click', '.foodord-topping-card__more', this.toggleCategories);

			// Save changes when WooCommerce saves product
			$('#publish, #save-post').on('click', this.saveSettings);
		},

		/**
		 * Setup drag and drop functionality
		 */
		setupDragDrop: function() {
			const $container = $('.foodord-topping-panel__sets');

			if ($container.length) {
					// Initialize jQuery UI sortable
					$container.sortable({
						handle: '.foodord-topping-card__drag-handle',
						placeholder: 'foodord-topping-card--placeholder',
						opacity: 0.8,
						cursor: 'move',
						axis: 'y',
						tolerance: 'intersect',
						containment: $container,
						scroll: true,
						scrollSensitivity: 20,
						scrollSpeed: 10,
						helper: 'clone',
						start: function(event, ui) {
							ui.helper.addClass('is-dragging');
							ui.placeholder.height(ui.item.outerHeight());
							// Keep helper within container bounds
							ui.helper.css({
								'max-width': $container.width() - 20,
								'z-index': 1000
							});
						},
						stop: function(event, ui) {
							ui.item.removeClass('is-dragging');
						},
					update: function() {
						ProductDataToppingSets.updateOrder();
					}
					});

				// Add visual feedback for drag handles
				$('.foodord-topping-card__drag-handle').css('cursor', 'move');
				$container.attr('data-sortable', 'active');
			}
		},

		/**
		 * Handle toggle switch changes
		 */
		handleToggle: function() {
			const $card = $(this).closest('.foodord-topping-card');
			const isChecked = $(this).is(':checked');

			if (isChecked) {
				$card.addClass('is-selected');
			} else {
				$card.removeClass('is-selected');
			}

			// Visual feedback
			$card.addClass('is-toggling');
			setTimeout(() => {
				$card.removeClass('is-toggling');
			}, 300);
		},

		/**
		 * Toggle category display
		 */
		toggleCategories: function(e) {
			e.preventDefault();
			const $button = $(this);
			const $card = $button.closest('.foodord-topping-card');
			const $hiddenCategories = $card.find('.foodord-topping-card__meta-item .is-hidden');

			if ($hiddenCategories.length) {
				$hiddenCategories.removeClass('is-hidden');
				$button.text($button.data('less-label') || 'Show less');
			} else {
				// Hide extra categories again
				$card.find('.foodord-topping-card__meta-item').slice(2).addClass('is-hidden');
				$button.text($button.data('more-label'));
			}
		},

		/**
		 * Update sort order
		 */
		updateOrder: function() {
			const order = [];
			const $orderInput = $('#foodord_topping_sets_order');

			// Get current order of cards
			$('.foodord-topping-card').each(function() {
				const setId = $(this).data('set-id');
				if (setId) {
					order.push(setId);
				}
			});

			// Create hidden input if doesn't exist
			if ($orderInput.length === 0) {
				$('<input>').attr({
					type: 'hidden',
					id: 'foodord_topping_sets_order',
					name: 'foodord_topping_sets_order',
					value: JSON.stringify(order)
				}).appendTo('#woocommerce-product-data');
			} else {
				$orderInput.val(JSON.stringify(order));
			}
		},

		/**
		 * Save settings (for future use)
		 */
		saveSettings: function() {
			// This will be fully implemented when save functionality is added
			const selectedSets = [];

			$('.foodord-topping-card__enable:checked').each(function() {
				selectedSets.push($(this).val());
			});

			// Store selected sets for future processing
			return selectedSets;
		}
	};

	/**
	 * Initialize when document is ready
	 */
	$(document).ready(function() {
		// Only initialize on product edit pages
		if ($('#foodord_topping_sets_data').length) {
			ProductDataToppingSets.init();
		}
	});

})(jQuery);