(function ($) {
	'use strict';

	$(
		function () {
			// Determine premium mode from Template Mapping script localization (limits.max_templates > 1)
			var isPremium = false;
			try {
				if (window.momcsAmazonTemplateMapping && window.momcsAmazonTemplateMapping.limits) {
					var maxTemplates = parseInt(window.momcsAmazonTemplateMapping.limits.max_templates || 1, 10);
					isPremium = maxTemplates > 1;
				}
			} catch (e) { /* no-op */ }

			// In premium, do NOT preload any template mapping; wait until a template is selected
			if (!isPremium) {
				// Load existing mappings on page load with a small delay to ensure embedded views are initialized
				setTimeout(
					function () {
						loadSavedDefaultMappings();
					},
					100
				);
			}

			// Track accordion states
			const accordionStates = new Map();

			// Initialize accordion states
			$( '.momcs-mapping-accordion' ).each(
				function (index) {
					const $accordion = $( this );
					const id         = $accordion.attr( 'id' ) || 'accordion-' + index;
					$accordion.attr( 'id', id );
					accordionStates.set( id, false ); // All accordions collapsed by default
				}
			);

			// Handle accordion functionality
			$( document ).on(
				'click',
				'.momcs-mapping-accordion-header',
				function (e) {
					e.preventDefault();
					e.stopPropagation();

					const $accordion = $( this ).closest( '.momcs-mapping-accordion' );
					const $content   = $accordion.find( '.momcs-mapping-accordion-content' );
					const $toggle    = $( this ).find( '.momcs-mapping-accordion-toggle' );
					const id         = $accordion.attr( 'id' );

					// Get current state
					const isOpen = accordionStates.get( id );

					// Update state first
					accordionStates.set( id, ! isOpen );

					// Then animate
					if (isOpen) {
						$content.stop( true, true ).slideUp( 300 );
						$toggle.removeClass( 'dashicons-arrow-up-alt2' ).addClass( 'dashicons-arrow-down-alt2' );
					} else {
						$content.stop( true, true ).slideDown( 300 );
						$toggle.removeClass( 'dashicons-arrow-down-alt2' ).addClass( 'dashicons-arrow-up-alt2' );
					}
				}
			);

			// Ensure all accordions are collapsed by default
			$( '.momcs-mapping-accordion .momcs-mapping-accordion-content' ).hide();
			$( '.momcs-mapping-accordion .momcs-mapping-accordion-toggle' )
			.addClass( 'dashicons-arrow-down-alt2' )
			.removeClass( 'dashicons-arrow-up-alt2' );

			// Override loadSavedDefaultMappings to respect accordion states
			const originalLoadSavedDefaultMappings = loadSavedDefaultMappings;
			loadSavedDefaultMappings               = function () {
					originalLoadSavedDefaultMappings.call( this );

					// Restore accordion states after load
					$( '.momcs-mapping-accordion' ).each(
						function () {
							const id           = $( this ).attr( 'id' );
							const shouldBeOpen = accordionStates.get( id );
							const $content     = $( this ).find( '.momcs-mapping-accordion-content' );
							const $toggle      = $( this ).find( '.momcs-mapping-accordion-toggle' );

							if (shouldBeOpen) {
								$content.show();
								$toggle.removeClass( 'dashicons-arrow-down-alt2' ).addClass( 'dashicons-arrow-up-alt2' );
							} else {
								$content.hide();
								$toggle.removeClass( 'dashicons-arrow-up-alt2' ).addClass( 'dashicons-arrow-down-alt2' );
							}
						}
					);
			};

			// Hide template mapping save button as we're using a consolidated button
			$( '#momcs-template-mapping-save' ).hide();

			// Mapping save functionality is now handled by the Next button in the stepper

			// Comprehensive validation function for all mappings
			// Premium behavior: If no template is selected AND no WC category is selected,
			// allow the user to proceed without validation (they don't want to edit any template).
			// Free behavior: Always require both WC and Amazon category selection.
			function validateAllMappings() {
				const validationResult = {
					isValid: true,
					errors: [],
					defaultFieldErrors: [],
					templateFieldErrors: [],
					skipped: false
				};

				// Clear previous error styling
				clearValidationErrors();

				const wcCat = $( '.momcs-template-mapping-wc-category' ).val();
				const templateSelected = $( '#momcs-template-select' ).val();

				// Premium mode: If no template AND no WC category selected, allow skipping
				// This means the user doesn't want to edit any template mapping
				if (isPremium && !templateSelected && !wcCat) {
					validationResult.skipped = true;
					return validationResult;
				}

				// 1. Validate default fields (all required)
				const defaultFields     = ['sku', 'item_name', 'brand', 'price', 'quantity'];
				const defaultFieldNames = {
					sku: 'SKU',
					item_name: 'Item Name',
					brand: 'Brand',
					price: 'Price',
					quantity: 'Quantity'
				};

				defaultFields.forEach(
					function (fieldKey) {
						const $select    = $( 'select[name="amazon_mapping[' + fieldKey + ']"\]' );
						const fieldValue = $select.val();
						const fieldName  = defaultFieldNames[fieldKey];

						if ( ! fieldValue || fieldValue === '') {
								validationResult.isValid = false;
								validationResult.defaultFieldErrors.push( fieldName );
								validationResult.errors.push( fieldName + ' field mapping is required' );

								// Add error styling
								$select.addClass( 'momcs-mapping-field-error' );
						}
					}
				);

				// 2. Validate template fields (if category is selected).
				const selectedCategory = $( '.momcs-template-mapping-amazon-category' ).val();
				if (selectedCategory && selectedCategory !== '') {
							$( '.momcs-field-mapping-row[data-required="true"]' ).each(
								function () {
									const $row        = $( this );
									const $select     = $row.find( '.momcs-field-mapping-row-wc-field' );
									const $enumSelect = $row.find( '.momcs-enum-select' );
									const enumValue   = $enumSelect.val();
									const fieldValue  = $select.val();
									const amazonField = $select.data( 'amazon-field' );

									if (( ! fieldValue || fieldValue === '') && ( ! enumValue || enumValue === '')) {
										validationResult.isValid = false;
										validationResult.templateFieldErrors.push( amazonField );
										validationResult.errors.push( 'Template field "' + amazonField + '" is required when category is selected' );

										// Add error styling
										$row.addClass( 'momcs-mapping-field-error' );
										$select.addClass( 'momcs-mapping-field-error' );
										$enumSelect.addClass( 'momcs-mapping-field-error' );
									}
								}
							);
				}

				// Validate WooCommerce category selection in each mapping row.
				// Only validate if in free mode OR if template/WC category is already selected
				const requireWcCategory = !isPremium || templateSelected || wcCat;
				if (requireWcCategory) {
					let wcCategoryErrorAdded = false;
					$( '.momcs-template-mapping-wc-category' ).each(
						function () {
							const $wcSelect = $( this );
							if ( ! $wcSelect.val()) {
									validationResult.isValid = false;
								if ( ! wcCategoryErrorAdded) {
									validationResult.errors.push( momcs_mapping_params.i18n_select_wc_category );
									wcCategoryErrorAdded = true;
								}
								$wcSelect.addClass( 'momcs-mapping-field-error' );
							}
						}
					);
				}

				// Validate Amazon category - only required if WC category OR template is selected
				// In free mode: Always require Amazon category
				// In premium mode: Only require if WC category or template is selected
				const requireAmazonCategory = !isPremium || wcCat || templateSelected;
				const firstAmazonCategory = $( '.momcs-template-mapping-amazon-category' ).val();
				if (requireAmazonCategory && ! firstAmazonCategory) {
							validationResult.isValid = false;
							validationResult.errors.push( momcs_mapping_params.i18n_select_amazon_category );
							$( '.momcs-template-mapping-amazon-category' ).addClass( 'momcs-mapping-field-error' );
				}

				return validationResult;
			}

			// Function to clear validation errors
			function clearValidationErrors() {
				$( '.momcs-mapping-field-error' ).removeClass( 'momcs-mapping-field-error' );
				$( '#momcs-mapping-validation-container' ).hide().empty();
			}

			// Function to display validation errors
			function displayValidationErrors(validationResult) {
				if ( ! validationResult.isValid) {
					let errorHtml = '<div class="momcs-mapping-validation-summary">';
					errorHtml    += '<span class="dashicons dashicons-warning"></span>';
					errorHtml    += momcs_mapping_params.i18n_fix_errors;
					errorHtml    += '<ul>';

					validationResult.errors.forEach(
						function (error) {
							errorHtml += '<li>' + error + '</li>';
						}
					);

					errorHtml += '</ul></div>';

					$( '#momcs-mapping-validation-container' ).html( errorHtml ).show();

					// Scroll to error container
					$( '#momcs-mapping-validation-container' )[0].scrollIntoView(
						{
							behavior: 'smooth',
							block: 'center'
						}
					);
				} else {
					const successHtml = '<div class="momcs-mapping-validation-success">' +
					'<span class="dashicons dashicons-yes-alt"></span>' +
					momcs_mapping_params.i18n_all_good +
					'</div>';
					$( '#momcs-mapping-validation-container' ).html( successHtml ).show();

					setTimeout(
						function () {
							$( '#momcs-mapping-validation-container' ).fadeOut();
						},
						3000
					);
				}
			}

			// Enhanced utility function to collect all mapping data with validation
			// Handles premium skip logic when no template/WC category is selected
			function collectAllMappingData() {
				const validationResult = validateAllMappings();

				// Premium mode: If validation was skipped (no template/WC category selected), allow proceeding
				if (validationResult.skipped) {
					return {
						validation: validationResult,
						isValid: true,
						skipped: true,
						mapping_data: '{}',
						category_mapping: '[]',
						field_mapping: '{}',
						selected_category: ''
					};
				}

				// Display validation results
				displayValidationErrors( validationResult );

				// If validation fails, return validation result instead of data
				if ( ! validationResult.isValid) {
					return {
						validation: validationResult,
						isValid: false
					};
				}

				// If validation passes, collect the data
				const formArray  = $( '#momcs-mapping-form :input' ).serializeArray();
				const formObject = {};

				$.each(
					formArray,
					function (i, field) {
						const matches = field.name.match( /amazon_mapping\[(.*?)\]/ );
						if (matches) {
							const key       = matches[1];
							formObject[key] = field.value;
						}
					}
				);

				// Collect template mapping data
				const categoryMappings = [];
				$( '.momcs-template-mapping-row' ).each(
					function () {
						const $row           = $( this );
						const wcCategory     = $row.find( '.momcs-template-mapping-wc-category' ).val();
						const amazonCategory = $row.find( '.momcs-template-mapping-amazon-category' ).val();

						if (wcCategory && amazonCategory) {
							categoryMappings.push(
								{
									wc_category: wcCategory,
									amazon_category: amazonCategory
								}
							);
						}
					}
				);

				// Collect field mapping data
				const fieldMappings = {};
				$( '.momcs-field-mapping-row' ).each(
					function () {
						const $row        = $( this );
						const amazonField = $row.closest( '.momcs-field-mapping-row' ).data( 'field' );
						const wcField     = $row.find( '.momcs-field-mapping-row-wc-field' ).val();
						const enumValue   = $row.find( '.momcs-enum-select' ).val();
						const chosenValue = wcField || enumValue;

						if (amazonField && chosenValue) {
							const arrayMatch = amazonField.match( /^([^\[]+)(?:\[]\.)?(.+)?$/ );
							if (arrayMatch) {
								const baseField = arrayMatch[1];
								const property  = arrayMatch[2];
								if (property) {
										fieldMappings[baseField]           = fieldMappings[baseField] || {};
										fieldMappings[baseField][property] = chosenValue;
								} else {
									fieldMappings[baseField] = chosenValue;
								}
							} else {
								fieldMappings[amazonField] = chosenValue;
							}
						}
					}
				);

				const selectedCategory = $( '.momcs-template-mapping-amazon-category' ).val();

				return {
					validation: validationResult,
					isValid: true,
					mapping_data: JSON.stringify( formObject ),
					category_mapping: JSON.stringify( categoryMappings ),
					field_mapping: JSON.stringify( fieldMappings ),
					selected_category: selectedCategory
				};
			}

			// Make the function globally available for the stepper
			window.collectAmazonMappingData = collectAllMappingData;

			// Function to load saved default mappings
			function loadSavedDefaultMappings() {
				$.ajax(
					{
						url: momcs_mapping_params.ajaxurl,
						type: 'POST',
						data: {
							action: 'momcs_sync_get_unified_mapping',
							marketplace: 'amazon',
							security: momcs_mapping_params.nonce_get_unified_mapping
						},
						success: function (response) {
							if (response.success) {
								// Load default mappings
								if (response.data.default_mappings) {
									const defaultMappings = response.data.default_mappings;

									// Populate the form fields with saved values
									for (const key in defaultMappings) {
										if ( ! Object.prototype.hasOwnProperty.call( defaultMappings, key )) {
											continue;
										}
											const fieldValue = defaultMappings[key];
											const $select    = $( 'select[name="amazon_mapping[' + key + ']"\]' );
										if ($select.length && fieldValue) {
											$select.val( fieldValue );
										}
									}
								}

								// Load template mappings (category mappings and selected category)
								if (response.data.category_mappings || response.data.selected_category) {
									loadSavedTemplateMappings( response.data );
								}
							}
						},
						error: function () {
							// Silent fail – defaults will be used
							// console.log('Could not load saved mappings - using defaults');
						}
					}
				);
			}

			// Function to load saved template mappings
			function loadSavedTemplateMappings(templateData) {
				const categoryMappings = templateData.category_mappings || [];
				const selectedCategory = templateData.selected_category || '';

				if (categoryMappings.length > 0) {
					// Populate existing category mappings
					categoryMappings.forEach(
						function (mapping, index) {
							if (index === 0) {
								// Update the first row
								$( '.momcs-template-mapping-wc-category:first' ).val( mapping.wc_category );
								$( '.momcs-template-mapping-amazon-category:first' ).val( mapping.amazon_category );
							} else {
								// Clone the first row to create additional mapping rows
								const $firstRow = $( '.momcs-template-mapping-row:first' );
								const $newRow   = $firstRow.clone();

								// Clear the values and set the new mapping values
								$newRow.find( '.momcs-template-mapping-wc-category' ).val( mapping.wc_category );
								$newRow.find( '.momcs-template-mapping-amazon-category' ).val( mapping.amazon_category );

								// Append the new row
								$( '#momcs-template-mapping-rows' ).append( $newRow );
							}
						}
					);
				} else if (selectedCategory) {
					// If no category mappings but we have a selected category, set it in the first row
					$( '.momcs-template-mapping-amazon-category:first' ).val( selectedCategory );
				}

				// If we have a selected category, trigger the field mapping loading
				if (selectedCategory) {
					setTimeout(
						function () {
							$( '.momcs-template-mapping-amazon-category:first' ).trigger( 'change' );
						},
						100
					);
				}
			}

			// Real-time validation on field changes
			$( document ).on(
				'change',
				'.momcs-mapping-select',
				function () {
					const $select = $( this );
					if ($select.val() && $select.val() !== '') {
						$select.removeClass( 'momcs-mapping-field-error' );

						// Check if all errors are resolved and hide validation container
						setTimeout(
							function () {
								const currentValidation = validateAllMappings();
								if (currentValidation.isValid) {
									clearValidationErrors();
								}
							},
							100
						);
					}
				}
			);

			// Real-time validation on template field changes
			$( document ).on(
				'change',
				'.momcs-field-mapping-row-wc-field, .momcs-enum-select',
				function () {
					const $select = $( this );
					const $row    = $select.closest( '.momcs-field-mapping-row' );

					if ($select.val() && $select.val() !== '') {
						$select.removeClass( 'momcs-mapping-field-error' );
						$row.removeClass( 'momcs-mapping-field-error' );

						// Check if all errors are resolved
						setTimeout(
							function () {
								const currentValidation = validateAllMappings();
								if (currentValidation.isValid) {
									clearValidationErrors();
								}
							},
							100
						);
					}
				}
			);

			// Utility function to programmatically trigger the template mapping save
			function saveTemplateMappings() {
					const $templateSaveBtn = $( '#momcs-template-mapping-save' );
				if ($templateSaveBtn.length) {
					$templateSaveBtn.trigger( 'click' );
				}
			}
		}
	);
})( jQuery );
