/* ==========================================================================
   SEOvault AI — Onboarding Wizard JavaScript
   ========================================================================== */

(function($) {
	'use strict';

	var Onboarding = {
		/**
		 * Initialize the onboarding wizard UI.
		 */
		init: function() {
			this.initCopyButtons();
			this.initValidation();
			this.initStepTransitions();
			this.initOptionCards();
			this.initMediaUploaders();
			this.initCharCounters();
		},

		/**
		 * Copy the provided text to the clipboard and show brief feedback.
		 *
		 * @param {string} text Text to copy.
		 * @param {jQuery} $button Button element to animate.
		 * @return {boolean}
		 */
		copyToClipboard: function(text, $button) {
			if (!text) {
				return false;
			}

			var copied = false;
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(text).then(function() {
					Onboarding.showCopyFeedback($button);
				});
				copied = true;
			} else {
				var $temp = $('<input type="text" value="" />');
				$('body').append($temp);
				$temp.val(text).select();
				try {
					document.execCommand('copy');
					Onboarding.showCopyFeedback($button);
					copied = true;
				} catch (err) {
					copied = false;
				}
				$temp.remove();
			}

			return copied;
		},

		/**
		 * Show a brief "Copied!" message on a button and restore it.
		 *
		 * @param {jQuery} $button Button element.
		 */
		showCopyFeedback: function($button) {
			if (!$button || !$button.length) {
				return;
			}
			var originalHtml = $button.html();
			var copiedText = (window.seovaultseo_onboarding && window.seovaultseo_onboarding.copied_text)
				? window.seovaultseo_onboarding.copied_text
				: 'Copied!';
			$button.html('<span class="dashicons dashicons-yes-alt"></span> ' + copiedText);
			setTimeout(function() {
				$button.html(originalHtml);
			}, 2000);
		},

		/**
		 * Bind copy buttons inside the onboarding wizard.
		 */
		initCopyButtons: function() {
			$(document).on('click', '.seovaultseo-copy-key', function(e) {
				e.preventDefault();
				var $btn = $(this);
				var key = $btn.data('key') || '';
				Onboarding.copyToClipboard(key, $btn);
			});
		},

		/**
		 * Validate a single required field.
		 *
		 * @param {HTMLElement} field Form field.
		 * @return {boolean}
		 */
		validateField: function(field) {
			var $field = $(field);
			var value = $field.val();
			var isValid = true;
			var $container = $field.closest('.seovaultseo-wizard-field');
			var $error = $container.find('.seovaultseo-wizard-error');
			var message = $field.data('error-message') || $error.data('message') || (typeof seovaultseo_onboarding !== 'undefined' && seovaultseo_onboarding.field_required) || 'This field is required.';

			if ($field.prop('required') && (!value || !value.toString().trim())) {
				isValid = false;
				$field.addClass('seovaultseo-wizard-input-error');
				if ($error.length) {
					$error.text(message);
				} else {
					$container.append(
						$('<div>')
							.addClass('seovaultseo-wizard-error')
							.attr('role', 'alert')
							.text(message)
					);
				}
			} else {
				$field.removeClass('seovaultseo-wizard-input-error');
				if ($error.length) {
					$error.text('');
				}
			}

			return isValid;
		},

		/**
		 * Validate all required fields inside the current wizard step.
		 *
		 * @return {boolean}
		 */
		validateCurrentStep: function() {
			var isValid = true;
			$('.seovaultseo-wizard-step-content').find('input, select, textarea').each(function() {
				if (!Onboarding.validateField(this)) {
					isValid = false;
				}
			});
			return isValid;
		},

		/**
		 * Bind inline validation on blur/input events.
		 */
		initValidation: function() {
			$(document).on('blur input change', '.seovaultseo-wizard-step-content input, .seovaultseo-wizard-step-content select, .seovaultseo-wizard-step-content textarea', function() {
				Onboarding.validateField(this);
			});
		},

		/**
		 * Validate the form before advancing to the next step.
		 */
		initStepTransitions: function() {
			$(document).on('submit', '.seovaultseo-wizard-form', function(e) {
				var $form = $(this);
				var action = $form.find('button[type="submit"][name="seovaultseo_step_action"]:focus').val();
				if (!action) {
					action = $form.find('input[name="seovaultseo_step_action"]').val();
				}
				if ('next' === action) {
					if (!Onboarding.validateCurrentStep()) {
						e.preventDefault();
						return false;
					}
				}
				return true;
			});
		},

		/**
		 * Toggle selected class on option cards when their radio changes.
		 */
		initOptionCards: function() {
			$(document).on('change', '.seovaultseo-wizard-option-card input[type="radio"]', function() {
				var $radio = $(this);
				var name = $radio.attr('name');
				$('.seovaultseo-wizard-option-card input[type="radio"][name="' + name + '"]').each(function() {
					var $card = $(this).closest('.seovaultseo-wizard-option-card');
					if (this.checked) {
						$card.addClass('seovaultseo-wizard-option-card-selected');
					} else {
						$card.removeClass('seovaultseo-wizard-option-card-selected');
					}
				});
			});
		},

		/**
		 * Initialize WordPress media uploader buttons for logo and social image.
		 */
		initMediaUploaders: function() {
			var frame;

			$(document).on('click', '.seovaultseo-wizard-media-button', function(e) {
				e.preventDefault();
				var $button = $(this);
				var $container = $button.closest('.seovaultseo-wizard-media-upload');

				if (frame) {
					frame.close();
				}

				frame = wp.media({
					title: $button.text(),
					button: { text: $button.text() },
					multiple: false
				});

				frame.on('select', function() {
					var attachment = frame.state().get('selection').first().toJSON();
					var url = attachment.url || (attachment.sizes && attachment.sizes.full ? attachment.sizes.full.url : '');

					$container.find('.seovaultseo-wizard-media-id').val(attachment.id);
					$container.find('.seovaultseo-wizard-media-url').val(url);

					var $preview = $container.find('.seovaultseo-wizard-media-preview');
					$preview.empty().append($('<img>').attr('src', url).attr('alt', ''));

					$container.find('.seovaultseo-wizard-media-remove').show();
				});

				frame.open();
			});

			$(document).on('click', '.seovaultseo-wizard-media-remove', function(e) {
				e.preventDefault();
				var $container = $(this).closest('.seovaultseo-wizard-media-upload');
				$container.find('.seovaultseo-wizard-media-id').val(0);
				$container.find('.seovaultseo-wizard-media-url').val('');
				$container.find('.seovaultseo-wizard-media-preview').empty();
				$(this).hide();
			});
		},

		/**
		 * Initialize character counters for textareas with a data-max counter.
		 */
		initCharCounters: function() {
			$('.seovaultseo-wizard-char-counter').each(function() {
				var $counter = $(this);
				var targetId = $counter.data('target');
				var max = parseInt($counter.data('max'), 10) || 160;
				var $target = $('#' + targetId);

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

				function updateCount() {
					var len = $target.val().length;
					$counter.find('.seovaultseo-wizard-char-count').text(len);
					if (len > max) {
						$counter.css('color', 'var(--seovaultseo-error, #DC2626)');
					} else {
						$counter.css('color', 'var(--seovaultseo-muted, #6B7280)');
					}
				}

				updateCount();
				$target.on('input keyup change', updateCount);
			});
		}
	};

	$(document).ready(function() {
		if ($('.seovaultseo-wizard').length) {
			Onboarding.init();
		}
	});

	window.seovaultseoOnboarding = Onboarding;

})(jQuery);
