( function ( $, config ) {
	'use strict';

	if ( ! config ) {
		return;
	}

	var selected = {};
	var quantities = {};
	var currentSearch = '';
	var currentPage = 1;
	var searchTimer = null;
	var STORAGE_KEY = 'phoenix_wp_price_labels_admin_form_state';

	function pickerRepeatEnabled() {
		return !! config.pickerRepeat && $( '#phoenix_wp_price_labels_picker_repeat_enabled' ).is( ':checked' );
	}

	function updateHiddenField() {
		var ids = Object.keys( selected ).filter( function ( id ) {
			return selected[ id ];
		} );
		$( '#phoenix_wp_price_labels_picker_ids' ).val( ids.join( ',' ) );

		var qtyPairs = ids.map( function ( id ) {
			var count = parseInt( quantities[ id ], 10 );
			if ( ! count || count < 1 ) {
				count = 1;
			}
			if ( count > 99 ) {
				count = 99;
			}
			return id + ':' + count;
		} );
		$( '#phoenix_wp_price_labels_picker_quantities' ).val( qtyPairs.join( ',' ) );

		updateSelectedCount( ids.length );
		syncPickerQuantityFields();
		persistAdminFormState();
	}

	function collectAdminFormState() {
		var state = {
			pickerIds: $( '#phoenix_wp_price_labels_picker_ids' ).val() || '',
			pickerQuantities: $( '#phoenix_wp_price_labels_picker_quantities' ).val() || '',
			pickerRepeat: $( '#phoenix_wp_price_labels_picker_repeat_enabled' ).is( ':checked' ),
			productIds: $( '#phoenix_wp_price_labels_product_ids' ).val() || '',
			bulkCategories: [],
			bulkOnSale: $( 'input[name="bulk_filter_on_sale"]' ).is( ':checked' ),
			bulkInStock: $( 'input[name="bulk_filter_in_stock"]' ).is( ':checked' ),
			bulkPriceSince: $( '#phoenix_wp_price_labels_price_since' ).val() || '',
			labelRepeat: $( '#phoenix_wp_price_labels_label_repeat' ).val() || '1',
			bulkExpandVariations: $( 'input[name="bulk_expand_variations"][value="1"]' ).is( ':checked' ),
		};

		$( 'input[name="bulk_category_ids[]"]:checked' ).each( function () {
			state.bulkCategories.push( this.value );
		} );

		return state;
	}

	function persistAdminFormState() {
		try {
			sessionStorage.setItem( STORAGE_KEY, JSON.stringify( collectAdminFormState() ) );
		} catch ( e ) {
			// Ignore quota or privacy-mode errors.
		}
	}

	function restoreAdminFormState() {
		var serverPickerIds = ( $( '#phoenix_wp_price_labels_picker_ids' ).val() || '' ).trim();

		if ( serverPickerIds ) {
			return;
		}

		if ( ( $( '#phoenix_wp_price_labels_product_ids' ).val() || '' ).trim() ) {
			return;
		}

		if ( $( 'input[name="bulk_category_ids[]"]:checked' ).length ) {
			return;
		}

		if ( $( 'input[name="bulk_filter_on_sale"]' ).is( ':checked' ) || $( 'input[name="bulk_filter_in_stock"]' ).is( ':checked' ) ) {
			return;
		}

		if ( ( $( '#phoenix_wp_price_labels_price_since' ).val() || '' ).trim() ) {
			return;
		}

		var raw;

		try {
			raw = sessionStorage.getItem( STORAGE_KEY );
		} catch ( e ) {
			return;
		}

		if ( ! raw ) {
			return;
		}

		var state;

		try {
			state = JSON.parse( raw );
		} catch ( e ) {
			return;
		}

		if ( ! state || typeof state !== 'object' ) {
			return;
		}

		if ( state.pickerIds ) {
			$( '#phoenix_wp_price_labels_picker_ids' ).val( state.pickerIds );
		}

		if ( state.pickerQuantities && $( '#phoenix_wp_price_labels_picker_quantities' ).length ) {
			$( '#phoenix_wp_price_labels_picker_quantities' ).val( state.pickerQuantities );
		}

		if ( $( '#phoenix_wp_price_labels_picker_repeat_enabled' ).length ) {
			$( '#phoenix_wp_price_labels_picker_repeat_enabled' ).prop( 'checked', !! state.pickerRepeat );
		}

		if ( state.productIds !== undefined && $( '#phoenix_wp_price_labels_product_ids' ).length ) {
			$( '#phoenix_wp_price_labels_product_ids' ).val( state.productIds );
		}

		if ( Array.isArray( state.bulkCategories ) ) {
			$( 'input[name="bulk_category_ids[]"]' ).prop( 'checked', false );
			state.bulkCategories.forEach( function ( id ) {
				$( 'input[name="bulk_category_ids[]"][value="' + escAttr( String( id ) ) + '"]' ).prop(
					'checked',
					true
				);
			} );
		}

		if ( $( 'input[name="bulk_filter_on_sale"]' ).length ) {
			$( 'input[name="bulk_filter_on_sale"]' ).prop( 'checked', !! state.bulkOnSale );
		}

		if ( $( 'input[name="bulk_filter_in_stock"]' ).length ) {
			$( 'input[name="bulk_filter_in_stock"]' ).prop( 'checked', !! state.bulkInStock );
		}

		if ( $( '#phoenix_wp_price_labels_price_since' ).length && state.bulkPriceSince ) {
			$( '#phoenix_wp_price_labels_price_since' ).val( state.bulkPriceSince );
		}

		if ( $( '#phoenix_wp_price_labels_label_repeat' ).length && state.labelRepeat ) {
			$( '#phoenix_wp_price_labels_label_repeat' ).val( state.labelRepeat );
		}

		if ( $( 'input[name="bulk_expand_variations"][value="1"]' ).length ) {
			$( 'input[name="bulk_expand_variations"][value="1"]' ).prop(
				'checked',
				state.bulkExpandVariations !== false
			);
		}
	}

	function syncPickerQuantityFields() {
		var showQty = pickerRepeatEnabled();

		$( '.phoenix-price-labels-for-woocommerce-picker__qty' ).each( function () {
			var $qty = $( this );
			var id = String( $qty.data( 'product-id' ) );
			var checked = !! selected[ id ];

			$qty.prop( 'hidden', ! showQty || ! checked );
			$qty.prop( 'disabled', ! showQty || ! checked );
		} );
	}

	function updateSelectedCount( count ) {
		$( '.phoenix-price-labels-for-woocommerce-picker__selected-count' ).text( count );
	}

	function renderProducts( products, append ) {
		var $list = $( '#phoenix-price-labels-for-woocommerce-product-list' );

		if ( ! append ) {
			$list.empty();
		}

		if ( ! products.length && ! append ) {
			$list.html(
				'<div class="phoenix-price-labels-for-woocommerce-picker__status">' +
					escHtml( config.i18n.empty ) +
					'</div>'
			);
			return;
		}

		products.forEach( function ( product ) {
			var id = String( product.id );
			var checked = !! selected[ id ];
			var qty = quantities[ id ] || 1;
			var $item = $(
				'<label class="phoenix-price-labels-for-woocommerce-picker__item">' +
					'<input type="checkbox" value="' +
					escAttr( id ) +
					'" ' +
					( checked ? 'checked' : '' ) +
					' />' +
					'<span class="phoenix-price-labels-for-woocommerce-picker__label">' +
					escHtml( product.label ) +
					'</span>' +
					'<input type="number" class="phoenix-price-labels-for-woocommerce-picker__qty" data-product-id="' +
					escAttr( id ) +
					'" min="1" max="99" step="1" value="' +
					escAttr( String( qty ) ) +
					'" hidden />' +
					'</label>'
			);

			$item.find( 'input[type="checkbox"]' ).on( 'change', function () {
				selected[ id ] = this.checked;
				if ( this.checked && ! quantities[ id ] ) {
					quantities[ id ] = 1;
				}
				updateHiddenField();
			} );

			$item.find( '.phoenix-price-labels-for-woocommerce-picker__qty' ).on( 'change input', function () {
				var value = parseInt( this.value, 10 );
				if ( ! value || value < 1 ) {
					value = 1;
				}
				if ( value > 99 ) {
					value = 99;
					this.value = '99';
				}
				quantities[ id ] = value;
				updateHiddenField();
			} );

			$list.append( $item );
		} );

		syncPickerQuantityFields();
	}

	function setLoading( isLoading ) {
		var $list = $( '#phoenix-price-labels-for-woocommerce-product-list' );

		if ( isLoading && ! $list.children().length ) {
			$list.html(
				'<div class="phoenix-price-labels-for-woocommerce-picker__status">' +
					escHtml( config.i18n.loading ) +
					'</div>'
			);
		}
	}

	function fetchProducts( append ) {
		setLoading( ! append );

		$.getJSON(
			config.ajaxUrl,
			{
				action: config.action,
				nonce: config.nonce,
				search: currentSearch,
				page: currentPage,
			}
		)
			.done( function ( response ) {
				if ( ! response || ! response.success ) {
					renderProducts( [], append );
					return;
				}

				renderProducts( response.data.products || [], append );
				$( '.phoenix-price-labels-for-woocommerce-picker__load-more' ).toggle(
					( response.data.products || [] ).length >= 20
				);
			} )
			.fail( function () {
				renderProducts( [], append );
			} );
	}

	function escHtml( text ) {
		return $( '<div>' ).text( text ).html();
	}

	function escAttr( text ) {
		return escHtml( text ).replace( /"/g, '&quot;' );
	}

	function initFromHiddenField() {
		var raw = $( '#phoenix_wp_price_labels_picker_ids' ).val() || '';
		var qtyRaw = $( '#phoenix_wp_price_labels_picker_quantities' ).val() || '';

		raw.split( ',' ).forEach( function ( part ) {
			var id = part.trim();
			if ( id ) {
				selected[ id ] = true;
				quantities[ id ] = quantities[ id ] || 1;
			}
		} );

		qtyRaw.split( ',' ).forEach( function ( segment ) {
			var pieces = segment.split( ':' );
			if ( 2 !== pieces.length ) {
				return;
			}
			var id = pieces[0].trim();
			var count = parseInt( pieces[1], 10 );
			if ( id && count > 0 ) {
				selected[ id ] = true;
				quantities[ id ] = Math.min( 99, count );
			}
		} );

		updateHiddenField();
	}

	$( function () {
		var $picker = $( '.phoenix-price-labels-for-woocommerce-picker' );

		if ( ! $picker.length ) {
			return;
		}

		restoreAdminFormState();
		initFromHiddenField();
		fetchProducts( false );

		$( '#phoenix_wp_price_labels_picker_repeat_enabled' ).on( 'change', function () {
			syncPickerQuantityFields();
			persistAdminFormState();
		} );

		$( '#phoenix-price-labels-for-woocommerce-search' ).on( 'input', function () {
			currentSearch = this.value.trim();
			currentPage = 1;

			clearTimeout( searchTimer );
			searchTimer = setTimeout( function () {
				fetchProducts( false );
			}, 300 );
		} );

		$( '.phoenix-price-labels-for-woocommerce-picker__load-more' ).on( 'click', function ( event ) {
			event.preventDefault();
			currentPage += 1;
			fetchProducts( true );
		} );
	} );

	$( function () {
		var $labelOnlyRows = $(
			'.phoenix-price-labels-for-woocommerce-layout-row, .phoenix-price-labels-for-woocommerce-style-row, .phoenix-price-labels-for-woocommerce-offset-row'
		);

		function clearAdminErrors() {
			$( '.phoenix-price-labels-for-woocommerce-admin-error' ).remove();

			if ( ! window.history.replaceState ) {
				return;
			}

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

			if ( ! url.searchParams.has( 'phoenix_wp_price_labels_error' ) ) {
				return;
			}

			url.searchParams.delete( 'phoenix_wp_price_labels_error' );
			window.history.replaceState( {}, '', url );
		}

		function syncOutputTypeFields() {
			var outputType = $( 'input[name="output_type"]:checked' ).val();
			var isOverview = outputType === 'overview';

			$labelOnlyRows.toggle( ! isOverview );
		}

		if ( $labelOnlyRows.length ) {
			$( 'input[name="output_type"]' ).on( 'change', syncOutputTypeFields );
			syncOutputTypeFields();
		}

		var $unitPricePanel = $( '.phoenix-price-labels-for-woocommerce-unit-price-panel' );
		var $unitPriceField = $( '#phoenix_wp_price_labels_field_unit_price' );

		function syncUnitPricePanel() {
			if ( ! $unitPricePanel.length || ! $unitPriceField.length ) {
				return;
			}

			if ( $unitPriceField.is( ':checked' ) ) {
				$unitPricePanel.prop( 'hidden', false );
			} else {
				$unitPricePanel.prop( 'hidden', true );
			}
		}

		if ( $unitPricePanel.length && $unitPriceField.length ) {
			$unitPriceField.on( 'change', syncUnitPricePanel );
			syncUnitPricePanel();
		}

		var $scanPanel = $( '.phoenix-price-labels-for-woocommerce-scan-panel' );
		var $barcodeField = $( '#phoenix_wp_price_labels_field_barcode' );

		function syncScanPanel() {
			if ( ! $scanPanel.length || ! $barcodeField.length ) {
				return;
			}

			if ( $barcodeField.is( ':checked' ) && ! $barcodeField.is( ':disabled' ) ) {
				$scanPanel.prop( 'hidden', false );
			} else {
				$scanPanel.prop( 'hidden', true );
			}
		}

		if ( $scanPanel.length && $barcodeField.length ) {
			$barcodeField.on( 'change', syncScanPanel );
			syncScanPanel();
		}

		var $eanField = $( '#phoenix_wp_price_labels_field_ean' );
		var $eanHint = $( '.phoenix-price-labels-for-woocommerce-field-settings__ean-hint' );
		var $barcodeHint = $( '.phoenix-price-labels-for-woocommerce-field-settings__barcode-hint' );
		var $barcodeTitleHint = $( '.phoenix-price-labels-for-woocommerce-field-settings__barcode-title-hint' );
		var $layoutSelect = $( '#phoenix_wp_price_labels_layout' );
		var scanCodeSingleTitleMaxMm = Number( config.i18n && config.i18n.scanCodeSingleTitleMaxMm ) || 35;

		function getSelectedLabelHeightMm() {
			if ( ! $layoutSelect.length ) {
				return 0;
			}

			var $option = $layoutSelect.find( 'option:selected' );

			return parseFloat( $option.attr( 'data-label-height' ) || '0' ) || 0;
		}

		function syncBarcodeTitleHint() {
			if ( ! $barcodeTitleHint.length ) {
				return;
			}

			var barcodeOn = $barcodeField.length && $barcodeField.is( ':checked' );
			var labelHeight = getSelectedLabelHeightMm();
			var compactLayout = labelHeight > 0 && labelHeight <= scanCodeSingleTitleMaxMm;

			$barcodeTitleHint.prop( 'hidden', ! barcodeOn || ! compactLayout );
		}

		function syncEanBarcodeExclusivity() {
			if ( ! $eanField.length || ! $barcodeField.length ) {
				return;
			}

			var barcodeOn = $barcodeField.is( ':checked' );
			var eanOn = $eanField.is( ':checked' );

			if ( barcodeOn && eanOn ) {
				$eanField.prop( 'checked', false );
				eanOn = false;
			}

			$barcodeField.prop( 'disabled', eanOn );
			$eanField.prop( 'disabled', barcodeOn );

			if ( $eanHint.length ) {
				$eanHint.prop( 'hidden', barcodeOn );
			}

			if ( $barcodeHint.length ) {
				$barcodeHint.prop( 'hidden', ! barcodeOn );
			}

			syncBarcodeTitleHint();
			syncScanPanel();
		}

		if ( $eanField.length && $barcodeField.length ) {
			$eanField.on( 'change', function () {
				if ( $eanField.is( ':checked' ) ) {
					$barcodeField.prop( 'checked', false );
				}
				syncEanBarcodeExclusivity();
			} );

			$barcodeField.on( 'change', function () {
				if ( $barcodeField.is( ':checked' ) ) {
					$eanField.prop( 'checked', false );
				}
				syncEanBarcodeExclusivity();
			} );

			syncEanBarcodeExclusivity();
		}

		if ( $layoutSelect.length ) {
			$layoutSelect.on( 'change', syncBarcodeTitleHint );
			syncBarcodeTitleHint();
		}

		var $scanShopMode = $( '.phoenix-price-labels-for-woocommerce-scan-shop-mode' );
		var $scanAutoRows = $( '.phoenix-price-labels-for-woocommerce-scan-panel__auto-row' );
		var $scanFormatRow = $( '.phoenix-price-labels-for-woocommerce-scan-panel__format-row' );

		function syncScanShopMode() {
			if ( ! $scanShopMode.length ) {
				return;
			}

			var shopMode = $scanShopMode.filter( ':checked' ).val() || 'auto';
			var isAuto = shopMode === 'auto';

			$scanAutoRows.toggle( isAuto );
			$scanFormatRow.toggle( isAuto );
		}

		if ( $scanShopMode.length ) {
			$scanShopMode.on( 'change', syncScanShopMode );
			syncScanShopMode();
		}

		$( document ).on(
			'change input',
			'#phoenix_wp_price_labels_product_ids, #phoenix-price-labels-for-woocommerce-search, .phoenix-price-labels-for-woocommerce-picker__item input, .phoenix-price-labels-for-woocommerce-bulk input, .phoenix-price-labels-for-woocommerce-bulk select',
			clearAdminErrors
		);

		$( document ).on(
			'change input',
			'#phoenix_wp_price_labels_product_ids, .phoenix-price-labels-for-woocommerce-bulk input, .phoenix-price-labels-for-woocommerce-bulk select',
			persistAdminFormState
		);

		$( '.wrap form[method="post"]' ).on( 'submit', persistAdminFormState );
	} );
} )( jQuery, window.phoenixWpPriceLabelsAdmin );
