/**
 * 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]
 * Chrome (focus trap, Esc, backdrop, close X, focus-return) comes from
 * SiteStaffrModal.enhance(); this file owns only the stepper math.
 */
(function($) {
	'use strict';

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

		var modalEl = document.getElementById('sitestaffr-buy-modal');
		if (!modalEl || !window.SiteStaffrModal) {
			return;
		}

		var controller = window.SiteStaffrModal.enhance(modalEl, {
			onOpen: function() {
				$('#sitestaffr-addon-quantity').val(MIN_QTY);
				updateModalDisplay();
			}
		});

		function updateModalDisplay() {
			var $quantityInput = $('#sitestaffr-addon-quantity');
			var qty = parseInt($quantityInput.val(), 10) || MIN_QTY;
			qty = Math.max(MIN_QTY, Math.min(MAX_QTY, qty));
			$quantityInput.val(qty);
			$('#sitestaffr-buy-quantity').val(qty);

			$('#sitestaffr-modal-minutes').text((qty * ADDON_MINUTES) + ' minutes');
			$('#sitestaffr-modal-price').text('$' + (qty * ADDON_PRICE));

			$(modalEl).find('.sitestaffr-stepper-minus').prop('disabled', qty <= MIN_QTY);
			$(modalEl).find('.sitestaffr-stepper-plus').prop('disabled', qty >= MAX_QTY);
		}

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

		// Cancel button (close X + backdrop + Esc are component-handled)
		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-modal-cancel', function(e) {
			e.preventDefault();
			controller.close();
		});

		// Steppers
		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-stepper-minus', function(e) {
			e.preventDefault();
			var $quantityInput = $('#sitestaffr-addon-quantity');
			$quantityInput.val((parseInt($quantityInput.val(), 10) || MIN_QTY) - 1);
			updateModalDisplay();
		});

		$(document).on('click', '#sitestaffr-buy-modal .sitestaffr-stepper-plus', function(e) {
			e.preventDefault();
			var $quantityInput = $('#sitestaffr-addon-quantity');
			$quantityInput.val((parseInt($quantityInput.val(), 10) || MIN_QTY) + 1);
			updateModalDisplay();
		});

		// Direct input edits
		$(document).on('input change', '#sitestaffr-addon-quantity', updateModalDisplay);

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