jQuery(document).ready(function ($) {

	const selectedOrders = sessionStorage.getItem('posten_order_ids')?.split(",") || [];

	function isValidOrderId(id) {
		return /^[A-Za-z0-9_-]+$/.test(id);
	}

	if (selectedOrders.length > 0) {
		selectedOrders.forEach(function (id) {
			if (!isValidOrderId(id)) return;
			$('.wp-list-table input[id="cb-select-' + id + '"][value="' + id + '"]')
				.prop('checked', true)
				.trigger('change');
		});
		sessionStorage.removeItem('posten_order_ids');
	}

	$(document).on('click', '#doaction, #doaction2', function (e) {
		var bulkAction = $('select[name="action"]').val() || $('select[name="action2"]').val();
		if (bulkAction === 'posten_bring_checkout_mass_booking_bulk_action') {
			e.preventDefault();
			var posten_order_ids = [];
			sessionStorage.setItem('posten_order_ids', "");
			const event = new Event('posten-order-ids-changed');
			window.dispatchEvent(event);

			$('input[name="id[]"]:checked').each(function () {
				posten_order_ids.push($(this).val());
			});
			$('input[name="post[]"]:checked').each(function () {
				posten_order_ids.push($(this).val());
			});
			if (posten_order_ids.length > 0) {
				sessionStorage.setItem('posten_order_ids', posten_order_ids.join(","));
				window.dispatchEvent(event);
				$('#posten-bring-custom-modal').addClass('visible').attr('aria-hidden', 'false');
			}
		}
	});


	$(document).on('click', '#close-posten-bring-modal', function () {
		$('#posten-bring-custom-modal').removeClass('visible');
		location.reload();
	});

	$(document).on('keydown', function (event) {
		if (event.key === 'Escape' && $('#posten-bring-custom-modal').hasClass('visible')) {
			$('#posten-bring-custom-modal').removeClass('visible');
			location.reload();
		}
	});

	$('.components-modal__screen-overlay').on('click', function (event) {
		if (event.target === this) {
			$('#posten-bring-custom-modal').removeClass('visible').attr('aria-hidden', 'true');
		}
	});
});
