/**
 * Signocore Multilanguage - Setup Wizard JavaScript
 *
 * @package Signocore\Multilanguage
 */

(function ($) {
	'use strict';

	var Wizard = {
		currentStep: 1,
		totalSteps: 3,

		/**
		 * Initialize the wizard.
		 */
		init: function () {
			if (!$('.sml-wizard').length) {
				return;
			}

			this.bindNavigation();
			this.bindLanguageSearch();
			this.bindLanguageCheckboxes();
			this.bindSkip();
			this.updateNavState();
		},

		/**
		 * Send an AJAX request with nonce verification.
		 *
		 * @param {string} action - WordPress AJAX action name.
		 * @param {Object} data   - Additional data to send.
		 * @returns {jQuery.Deferred}
		 */
		ajax: function (action, data) {
			data = data || {};
			data.action = action;
			data._ajax_nonce = smlAjax.nonce;

			return $.ajax({
				url: smlAjax.url,
				type: 'POST',
				data: data,
				dataType: 'json',
			});
		},

		/**
		 * Bind next/back button handlers.
		 */
		bindNavigation: function () {
			var self = this;

			$(document).on('click', '.sml-wizard-next', function (e) {
				e.preventDefault();

				var $btn = $(this);
				if ($btn.prop('disabled')) {
					return;
				}

				self.saveStep(self.currentStep, $btn, function () {
					if (self.currentStep < self.totalSteps) {
						self.goToStep(self.currentStep + 1);
					} else {
						self.finish();
					}
				});
			});

			$(document).on('click', '.sml-wizard-back', function (e) {
				e.preventDefault();
				if (self.currentStep > 1) {
					self.goToStep(self.currentStep - 1);
				}
			});
		},

		/**
		 * Navigate to a specific step.
		 *
		 * @param {number} step
		 */
		goToStep: function (step) {
			this.currentStep = step;

			// Update step panels
			$('.sml-wizard-step').removeClass('active');
			$('.sml-wizard-step[data-step="' + step + '"]').addClass('active');

			// Update step indicators
			$('.sml-wizard-steps li').each(function () {
				var $li = $(this);
				var liStep = parseInt($li.data('step'), 10);

				$li.removeClass('active completed');
				if (liStep === step) {
					$li.addClass('active');
				} else if (liStep < step) {
					$li.addClass('completed');
				}
			});

			this.updateNavState();

			// Rebuild default language list when entering step 1's data is needed on step 2
			if (step === 2) {
				this.updateDefaultLanguageList();
			}
		},

		/**
		 * Update navigation button states.
		 */
		updateNavState: function () {
			var $back = $('.sml-wizard-back');
			var $next = $('.sml-wizard-next');

			$back.toggle(this.currentStep > 1);

			if (this.currentStep === this.totalSteps) {
				$next.text($next.data('finish-text') || 'Finish');
			} else {
				$next.text($next.data('next-text') || 'Next');
			}

			// Validate current step
			this.validateStep();
		},

		/**
		 * Validate the current step and enable/disable the next button.
		 */
		validateStep: function () {
			var $next = $('.sml-wizard-next');
			var valid = true;

			if (this.currentStep === 1) {
				var checked = $('.sml-language-grid input[type="checkbox"]:checked').length;
				valid = checked >= 2;
			}

			$next.prop('disabled', !valid);
		},

		/**
		 * Save the current step data via AJAX.
		 *
		 * @param {number}   step     - Step number to save.
		 * @param {jQuery}   $btn     - The button element for loading state.
		 * @param {Function} callback - Called on success.
		 */
		saveStep: function (step, $btn, callback) {
			var self = this;
			var data = this.getStepData(step);

			if (data === false) {
				return;
			}

			data.step = step;

			// Loading state
			$btn.prop('disabled', true);
			var originalText = $btn.text();
			$btn.html('<span class="spinner is-active" style="margin: 0 4px 0 0; float: left;"></span> Saving...');

			this.ajax('sml_wizard_save', data)
				.done(function (response) {
					if (response.success) {
						if (typeof callback === 'function') {
							callback(response.data);
						}
					} else {
						alert(response.data || 'An error occurred. Please try again.');
					}
				})
				.fail(function () {
					alert('A server error occurred. Please try again.');
				})
				.always(function () {
					$btn.prop('disabled', false).text(originalText);
					self.updateNavState();
				});
		},

		/**
		 * Collect form data for a specific step.
		 *
		 * @param {number} step
		 * @returns {Object|false}
		 */
		getStepData: function (step) {
			var data = {};

			switch (step) {
				case 1:
					var languages = [];
					$('.sml-language-grid input[type="checkbox"]:checked').each(function () {
						languages.push($(this).val());
					});

					if (languages.length < 2) {
						alert('Please select at least 2 languages.');
						return false;
					}

					data.languages = languages;
					data.default_language = $('input[name="sml_default_language"]:checked').val() || languages[0];
					break;

				case 2:
					data.url_strategy = $('input[name="sml_url_strategy"]:checked').val() || 'directory';
					data.hide_default_language_prefix = $('input[name="sml_hide_default_language_prefix"]').is(':checked') ? 1 : 0;
					break;

				case 3:
					// Final step - just marks completion
					break;
			}

			return data;
		},

		/**
		 * Finish the wizard and redirect.
		 */
		finish: function () {
			if (smlAjax.dashboardUrl) {
				window.location.href = smlAjax.dashboardUrl;
			} else {
				window.location.reload();
			}
		},

		/**
		 * Language search/filter on step 1.
		 */
		bindLanguageSearch: function () {
			$(document).on('input', '.sml-language-search input', function () {
				var query = $(this).val().toLowerCase().trim();
				var $grid = $(this).closest('.sml-wizard-step').find('.sml-language-grid');
				var visibleCount = 0;

				$grid.find('label').each(function () {
					var $label = $(this);
					var name = ($label.data('name') || '').toLowerCase();
					var native = ($label.data('native') || '').toLowerCase();
					var code = ($label.data('code') || '').toLowerCase();

					var matches = !query || name.indexOf(query) > -1 || native.indexOf(query) > -1 || code.indexOf(query) > -1;
					$label.toggle(matches);
					if (matches) {
						visibleCount++;
					}
				});

				// Show/hide no results message
				var $noResults = $grid.find('.sml-no-results');
				if (visibleCount === 0) {
					if (!$noResults.length) {
						$grid.append('<div class="sml-no-results">No languages found.</div>');
					}
					$noResults.show();
				} else {
					$noResults.hide();
				}
			});
		},

		/**
		 * Handle language checkbox changes for validation and visual state.
		 */
		bindLanguageCheckboxes: function () {
			var self = this;

			$(document).on('change', '.sml-language-grid input[type="checkbox"]', function () {
				var $label = $(this).closest('label');
				$label.toggleClass('checked', this.checked);
				self.validateStep();
			});
		},

		/**
		 * Update the default language radio list based on selected checkboxes.
		 */
		updateDefaultLanguageList: function () {
			var $list = $('.sml-default-language-list');
			if (!$list.length) {
				return;
			}

			var currentDefault = $('input[name="sml_default_language"]:checked').val();
			$list.empty();

			$('.sml-language-grid input[type="checkbox"]:checked').each(function () {
				var $cb = $(this);
				var code = $cb.val();
				var name = $cb.closest('label').data('name') || code;
				var isChecked = code === currentDefault ? ' checked' : '';

				if (!currentDefault && $list.children().length === 0) {
					isChecked = ' checked';
				}

				$list.append(
					'<li>' +
						'<label>' +
						'<input type="radio" name="sml_default_language" value="' + code + '"' + isChecked + '> ' +
						name +
						'</label>' +
					'</li>'
				);
			});
		},

		/**
		 * Skip wizard functionality.
		 */
		bindSkip: function () {
			$(document).on('click', '.sml-wizard-skip', function (e) {
				e.preventDefault();

				var $link = $(this);

				if (!confirm('Are you sure you want to skip the setup wizard? You can configure these settings later.')) {
					return;
				}

				$link.css('opacity', '0.5').css('pointer-events', 'none');

				Wizard.ajax('sml_wizard_skip')
					.done(function (response) {
						if (response.success) {
							if (smlAjax.dashboardUrl) {
								window.location.href = smlAjax.dashboardUrl;
							} else {
								window.location.reload();
							}
						} else {
							alert(response.data || 'An error occurred.');
							$link.css('opacity', '').css('pointer-events', '');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
						$link.css('opacity', '').css('pointer-events', '');
					});
			});
		},
	};

	$(document).ready(function () {
		Wizard.init();
	});
})(jQuery);
