(function($){
	'use strict';

	$(function(){
		var $list = $('#spar-earn-accordion-list');
		if ( ! $list.length ) { return; }

		/**
		 * Move every child accordion (data-parent-key) so it sits
		 * immediately after its parent accordion (data-key).
		 */
		function repositionChildAccordions() {
			$list.find('.spar-earn-accordion-child[data-parent-key]').each( function() {
				var $child  = $(this);
				var $parent = $list.find('.spar-earn-accordion[data-key="' + $child.data('parent-key') + '"]');
				if ( $parent.length ) {
					$parent.after( $child );
				}
			});
		}

		// Reorder accordion DOM elements to match saved order on page load.
		var savedOrder = window.sparEarnOrder || [];
		if ( savedOrder.length ) {
			savedOrder.forEach( function( key ) {
				var $item = $list.find( '.spar-earn-accordion[data-key="' + key + '"]' );
				if ( $item.length ) {
					$list.append( $item );
				}
			} );
		}
		// Move PRO-disabled stubs (no data-key) to the end so free items always appear first.
		$list.find( '.spar-premium-disabled' ).each( function() {
			$list.append( $(this) );
		} );
		// Snap child accordions into place after initial reorder.
		repositionChildAccordions();

		// Init jQuery UI sortable on the accordion list.
		// Only data-key accordions are sortable items; child accordions are excluded.
		if ( $.fn.sortable ) {
			$list.sortable({
				items: '.spar-earn-accordion[data-key]',
				handle: '.spar-drag-handle',
				axis: 'y',
				tolerance: 'pointer',
				placeholder: 'spar-earn-sortable-placeholder',
				forcePlaceholderSize: true,
				update: function() {
					repositionChildAccordions();
					$('#spar-settings-form').trigger('spar-save-settings');
				}
			});
		}

		// Checkbox names that control earn way visibility.
		var enabledCheckboxes = [
			'signup_enabled', 'order_enabled', 'order_fixed_enabled',
			'referral_enabled',
			'first_order_enabled', 'nth_order_enabled',
			'review_enabled', 'birthday_enabled', 'daily_login_enabled',
			'spin_wheel_enabled'
		];

		// Map from checkbox name to accordion data-key.
		var checkboxKeyMap = {
			'signup_enabled':      'signup',
			'order_enabled':       'order',
			'order_fixed_enabled': 'order_fixed',
			'referral_enabled':    'referral',
			'first_order_enabled': 'first_order',
			'nth_order_enabled':   'nth_order',
			'review_enabled':      'review',
			'birthday_enabled':    'birthday',
			'daily_login_enabled': 'daily_login',
			'spin_wheel_enabled':  'spin_wheel'
		};

		function syncDragHandle( $checkbox ) {
			var name   = $checkbox.attr('name');
			var wayKey = checkboxKeyMap[ name ];
			if ( ! wayKey ) { return; }
			var $accordion = $list.find( '.spar-earn-accordion[data-key="' + wayKey + '"]' );
			if ( ! $accordion.length ) { return; }

			var $handle = $accordion.find('.spar-drag-handle').first();
			if ( $checkbox.is(':checked') ) {
				$handle.css({ opacity: '', cursor: '', 'pointer-events': '' });
			} else {
				$handle.css({ opacity: '0.3', cursor: 'not-allowed', 'pointer-events': 'none' });
			}
		}

		// Initialise drag handle opacity based on current checkbox states.
		$.each( enabledCheckboxes, function( i, name ) {
			var $cb = $( 'input[name="' + name + '"]:not([disabled])' ).first();
			if ( $cb.length ) { syncDragHandle( $cb ); }
		} );

		// Listen on any non-disabled instance of each enable checkbox.
		$.each( enabledCheckboxes, function( i, name ) {
			$(document).on( 'change', 'input[name="' + name + '"]:not([disabled])', function() {
				syncDragHandle( $(this) );
			});
		});
	});
})(jQuery);
