/**
 * SiteStaffr — Buy More Minutes Modal (shared component)
 *
 * Works on any page that includes the buy-minutes-modal.php partial.
 * Open triggers: #sitestaffr-open-buy-modal OR [data-open-buy-modal]
 */
(function($) {
	'use strict';

	$(document).ready(function() {
		var ADDON_MINUTES = 50;
		var ADDON_PRICE = 10;
		var MIN_QTY = 1;
		var MAX_QTY = 10;

		var lastFocusedElement = null;

		function getModalElements() {
			var $modal = $('#sitestaffr-buy-modal');
			if (!$modal.length) {
				return null;
			}
			return {
				modal: $modal,
				quantityInput: $('#sitestaffr-addon-quantity'),
				hiddenQuantity: $('#sitestaffr-buy-quantity'),
				minusBtn: $modal.find('.sitestaffr-stepper-minus'),
				plusBtn: $modal.find('.sitestaffr-stepper-plus'),
				minutesDisplay: $('#sitestaffr-modal-minutes'),
				priceDisplay: $('#sitestaffr-modal-price')
			};
		}

		// Ensure fixed-position modal is attached to <body> so viewport centering is exact.
		(function ensureModalInBody() {
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $modal = elements.modal;
			if (!$modal.parent().is('body')) {
				$('body').append($modal);
			}
		})();

		function updateModalDisplay(elements) {
			if (!elements) {
				return;
			}
			var $quantityInput = elements.quantityInput;
			var qty = parseInt($quantityInput.val(), 10) || MIN_QTY;
			qty = Math.max(MIN_QTY, Math.min(MAX_QTY, qty));
			$quantityInput.val(qty);
			elements.hiddenQuantity.val(qty);

			var totalMinutes = qty * ADDON_MINUTES;
			var totalPrice = qty * ADDON_PRICE;

			elements.minutesDisplay.text(totalMinutes + ' minutes');
			elements.priceDisplay.text('$' + totalPrice);

			elements.minusBtn.prop('disabled', qty <= MIN_QTY);
			elements.plusBtn.prop('disabled', qty >= MAX_QTY);
		}

		function openModal() {
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $modal = elements.modal;
			lastFocusedElement = document.activeElement;
			elements.quantityInput.val(MIN_QTY);
			updateModalDisplay(elements);
			$modal.css({
				display: 'flex',
				alignItems: 'center',
				justifyContent: 'center'
			}).attr('aria-hidden', 'false');
			$modal.find('.sitestaffr-modal').focus();
			$('body').css('overflow', 'hidden');
		}

		function closeModal() {
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $modal = elements.modal;
			$modal.hide();
			$modal.attr('aria-hidden', 'true');
			$('body').css('overflow', '');
			if (lastFocusedElement) {
				lastFocusedElement.focus();
				lastFocusedElement = null;
			}
		}

		// Open modal triggers
		$(document).on('click', '#sitestaffr-open-buy-modal, [data-open-buy-modal]', function(e) {
			e.preventDefault();
			openModal();
		});

		// Close: X button or Cancel
		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-modal-close, #sitestaffr-buy-modal .sitestaffr-modal-cancel', function(e) {
			e.preventDefault();
			closeModal();
		});

		// Close: overlay click
		$(document).on('click', '#sitestaffr-buy-modal', function(e) {
			if ($(e.target).is('#sitestaffr-buy-modal')) {
				closeModal();
			}
		});

		// Close: Escape
		$(document).on('keydown', function(e) {
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $modal = elements.modal;
			if (e.key === 'Escape' && $modal.is(':visible')) {
				closeModal();
			}
		});

		// Stepper minus
		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-stepper-minus', function(e) {
			e.preventDefault();
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $quantityInput = elements.quantityInput;
			var qty = parseInt($quantityInput.val(), 10) || MIN_QTY;
			if (qty > MIN_QTY) {
				$quantityInput.val(qty - 1);
				updateModalDisplay(elements);
			}
		});

		// Stepper plus
		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-stepper-plus', function(e) {
			e.preventDefault();
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $quantityInput = elements.quantityInput;
			var qty = parseInt($quantityInput.val(), 10) || MIN_QTY;
			if (qty < MAX_QTY) {
				$quantityInput.val(qty + 1);
				updateModalDisplay(elements);
			}
		});

		// Focus trap
		$(document).on('keydown', function(e) {
			var elements = getModalElements();
			if (!elements) {
				return;
			}
			var $modal = elements.modal;
			if (!$modal.is(':visible') || e.key !== 'Tab') return;
			var $focusable = $modal.find('button:visible, input:visible, [tabindex]:not([tabindex="-1"])');
			if (!$focusable.length) return;
			var $first = $focusable.first();
			var $last = $focusable.last();
			if (e.shiftKey) {
				if (document.activeElement === $first[0] || !$.contains($modal[0], document.activeElement)) {
					e.preventDefault();
					$last.focus();
				}
			} else {
				if (document.activeElement === $last[0] || !$.contains($modal[0], document.activeElement)) {
					e.preventDefault();
					$first.focus();
				}
			}
		});

		// Sync quantity before submit
		$(document).on('submit', '#sitestaffr-buy-form', function() {
			updateModalDisplay(getModalElements());
		});
	});
})(jQuery);
