/**
 * Booking Form Builder — Frontend Form JS
 * Handles multi-step navigation, card choice interactions,
 * validation, AJAX submission and WooCommerce redirect.
 */
/* global formulatePricingFormData, jQuery */
(function ($) {
	'use strict';

	// ── Initialise every .bf-form-wrap on the page ───────────────────────────
	function initForms() {
		$('.bf-form-wrap').each(function () {
			initForm($(this));
		});
	}

	function initForm($wrap) {
		var formId    = $wrap.data('form-id');
		var multiStep = $wrap.data('multi-step') === 1 || $wrap.data('multi-step') === '1';
		var totalSteps = parseInt($wrap.data('steps') || 1, 10);
		var isPreview  = $wrap.data('preview') === 1 || $wrap.data('preview') === '1';
		var currentStep = 0;

		var $steps     = $wrap.find('.bf-step');
		var $form      = $wrap.find('.bf-dynamic-form');
		var $successWrap = $wrap.find('.bf-success-wrap');
		var $errorMsg  = $wrap.find('.bf-form-error-msg');
		var strings    = (formulatePricingFormData && formulatePricingFormData.strings) ? formulatePricingFormData.strings : {};

		var $checkoutLoading = $(
			'<div class="bf-checkout-loading" style="display:none" aria-hidden="true" role="alertdialog" aria-live="polite" aria-busy="true">' +
				'<div class="bf-checkout-loading-box">' +
					'<div class="bf-checkout-loading-spinner" aria-hidden="true"></div>' +
					'<p class="bf-checkout-loading-title"></p>' +
					'<p class="bf-checkout-loading-sub">' + (strings.redirectCheckout || 'Redirecting to checkout…') + '</p>' +
				'</div>' +
			'</div>'
		);
		$checkoutLoading.find('.bf-checkout-loading-title').text(strings.checkoutLoading || 'Preparing your order…');
		$('body').append($checkoutLoading);

		function showCheckoutLoading(message) {
			if (message) {
				$checkoutLoading.find('.bf-checkout-loading-title').text(message);
			}
			$checkoutLoading.attr('aria-hidden', 'false').fadeIn(200);
			$('body').addClass('bf-checkout-loading-active');
		}

		function hideCheckoutLoading() {
			$checkoutLoading.attr('aria-hidden', 'true').fadeOut(200);
			$('body').removeClass('bf-checkout-loading-active');
		}

		// ── Card choice toggle ────────────────────────────────────────────────
		$wrap.on('click', '.bf-card', function () {
			var $card  = $(this);
			var $group = $card.closest('.bf-card-group');
			var isMulti = $group.data('multi') === 1 || $group.data('multi') === '1';
			var $input = $card.find('input');

			if (isMulti) {
				$input.prop('checked', !$input.prop('checked'));
			} else {
				$group.find('input').prop('checked', false);
				$input.prop('checked', true);
			}
		});

		// ── Custom radio/checkbox toggle ──────────────────────────────────────
		$wrap.on('change', '.bf-radio-label input[type="radio"]', function () {
			var $group = $(this).closest('.bf-radio-group');
			$group.find('.bf-radio-label').each(function () {
				$(this).toggleClass('checked', $(this).find('input').is(':checked'));
			});
		});

		$wrap.on('change', '.bf-checkbox-label input[type="checkbox"]', function () {
			var $label = $(this).closest('.bf-checkbox-label');
			$label.toggleClass('checked', $(this).is(':checked'));
		});

		$wrap.on('change', '.bf-card-group input', function () {
			var $group = $(this).closest('.bf-card-group');
			$group.find('.bf-card').each(function () {
				$(this).toggleClass('checked', $(this).find('input').is(':checked'));
			});
		});

		// ── Multi-step navigation ─────────────────────────────────────────────
		if (multiStep) {
			// Next
			$wrap.on('click', '.bf-btn-next', function () {
				if (!validateStep($steps.eq(currentStep))) { return; }
				currentStep++;
				goToStep(currentStep);
			});

			// Prev
			$wrap.on('click', '.bf-btn-prev', function () {
				currentStep--;
				goToStep(currentStep);
			});
		}

		function goToStep(idx) {
			$steps.hide();
			$steps.eq(idx).show();

			// Update progress
			updateProgress(idx);

			// Scroll to form top
			$('html, body').animate({ scrollTop: $wrap.offset().top - 80 }, 300);
		}

		function updateProgress(stepIdx) {
			var pct = Math.round((stepIdx + 1) / totalSteps * 100);
			$wrap.find('.bf-progress-fill').css('width', pct + '%');

			$wrap.find('.bf-step-indicator').each(function (si) {
				$(this).removeClass('active done');
				if (si < stepIdx) { $(this).addClass('done'); }
				if (si === stepIdx) { $(this).addClass('active'); }
			});
		}

		// ── Validation ────────────────────────────────────────────────────────
		function validateStep($step) {
			var valid = true;

			// Clear previous errors
			$step.find('.bf-field-error').hide().text('');
			$step.find('.bf-input').removeClass('bf-field-invalid');

			$step.find('.bf-field-wrap').each(function () {
				var $fieldWrap = $(this);
				var type       = $fieldWrap.data('field-type');

				// Find required inputs
				var $inputs = $fieldWrap.find('input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]), textarea, select').filter('[required]');

				$inputs.each(function () {
					var $inp = $(this);
					var val  = $inp.val();
					if (!val || (Array.isArray(val) && !val.length)) {
						showFieldError($fieldWrap, 'This field is required.');
						$inp.addClass('bf-field-invalid');
						valid = false;
					} else if ($inp.attr('type') === 'email' && !isValidEmail(val)) {
						showFieldError($fieldWrap, 'Please enter a valid email address.');
						$inp.addClass('bf-field-invalid');
						valid = false;
					}
				});

				// Radio required
				var $radios = $fieldWrap.find('input[type="radio"][required]');
				if ($radios.length && !$radios.filter(':checked').length) {
					showFieldError($fieldWrap, 'Please select an option.');
					valid = false;
				}

				// Checkbox / card choice required
				var $cbGroup = $fieldWrap.find('.bf-checkbox-group[data-required="1"]');
				if ($cbGroup.length && !$cbGroup.find('input[type="checkbox"]:checked').length) {
					showFieldError($fieldWrap, 'Please select at least one option.');
					valid = false;
				}

				var $cardGroup = $fieldWrap.find('.bf-card-group[data-required="1"]');
				if ($cardGroup.length && !$cardGroup.find('input:checked').length) {
					showFieldError($fieldWrap, 'Please select at least one option.');
					valid = false;
				}
			});

			return valid;
		}

		function showFieldError($fieldWrap, msg) {
			var $err = $fieldWrap.find('.bf-field-error');
			$err.text(msg).show();
		}

		function isValidEmail(email) {
			return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
		}

		/** Sum data-price on all checked choice labels (multiple choice + cards). */
		function calculateSelectedTotal() {
			var total = 0;
			$form.find('input:checked').each(function () {
				var $priced = $(this).closest('label[data-price]');
				var price   = parseFloat($priced.attr('data-price'), 10);
				if (!isNaN(price) && price > 0) {
					total += price;
				}
			});
			return Math.round(total * 100) / 100;
		}

		// ── Form submission ───────────────────────────────────────────────────
		$form.on('submit', function (e) {
			e.preventDefault();

			if (isPreview) {
				alert('Preview mode: submissions are disabled.');
				return;
			}

			// Validate current (last) step
			if (!validateStep($steps.eq(currentStep))) { return; }

			var $submitBtn = $form.find('.bf-btn-submit');
			$submitBtn.prop('disabled', true).addClass('bf-btn-loading');
			$errorMsg.hide();
			showCheckoutLoading(strings.checkoutLoading || 'Preparing your order…');

			// Collect form data (serialize preserves formulate_pricing_fields[id][] arrays)
			var formData = $form.serialize();
			formData += '&action=formulate_pricing_submit_form&form_id=' + formId;
			formData += '&formulate_pricing_form_id=' + formId;

			$.post(formulatePricingFormData.ajaxUrl, formData, function (res) {
				if (res.success) {
					handleSuccess(res.data);
				} else {
					hideCheckoutLoading();
					$submitBtn.prop('disabled', false).removeClass('bf-btn-loading');
					handleError(res.data);
				}
			}).fail(function () {
				hideCheckoutLoading();
				$submitBtn.prop('disabled', false).removeClass('bf-btn-loading');
				$errorMsg.text('Network error. Please try again.').show();
			});
		});

		function handleSuccess(data) {
			if (data.redirect) {
				showCheckoutLoading(strings.redirectCheckout || 'Redirecting to checkout…');
				window.location.href = data.redirect;
				return;
			}
			hideCheckoutLoading();
			// Show success message
			$form.fadeOut(300, function () {
				$successWrap.fadeIn(300);
				if (data.success_message) {
					$wrap.find('.bf-success-text').html(data.success_message);
				}
			});
			$wrap.find('.bf-progress-wrap').fadeOut(200);
		}

		function handleError(data) {
			hideCheckoutLoading();
			var msg = data.message || 'An error occurred. Please try again.';
			$errorMsg.text(msg).show();

			// Highlight individual field errors
			if (data.errors) {
				$.each(data.errors, function (fieldId, errMsg) {
					var $fw = $wrap.find('[data-field-id="' + fieldId + '"]');
					$fw.find('.bf-field-error').text(errMsg).show();
					$fw.find('.bf-input').addClass('bf-field-invalid');

					// Find which step this field is on and go there
					var $step = $fw.closest('.bf-step');
					if ($step.length && multiStep) {
						var stepIdx = parseInt($step.data('step-index'), 10);
						if (!isNaN(stepIdx) && stepIdx !== currentStep) {
							currentStep = stepIdx;
							goToStep(currentStep);
						}
					}
				});
			}

			// Scroll to first error
			var $firstErr = $wrap.find('.bf-field-error:visible').first();
			if ($firstErr.length) {
				$('html, body').animate({ scrollTop: $firstErr.offset().top - 100 }, 300);
			}
		}
	}

	// ── Boot ──────────────────────────────────────────────────────────────────
	$(document).ready(function () {
		initForms();
	});

}(jQuery));
