(function ($) {
	'use strict';

	function initTableReservation() {
		$(document).off('submit.unlockafeTableReservation', '.unlockaddons_table_reservation_form');
		$(document).on('submit.unlockafeTableReservation', '.unlockaddons_table_reservation_form', function (e) {
			e.preventDefault();
			var $form = $(this);
			var $msg = $form.find('.unlockaddons_table_reservation_message');
			var $summary = $form.find('.unlockaddons_table_reservation_summary');
			var redirect = $form.data('redirect') || '';
			var showSummary = $form.data('show-summary') === 1 || $form.data('show-summary') === true;

			$msg.hide().removeClass('success error').text('');
			$summary.hide().empty();

			var formData = new FormData($form[0]);
			formData.append('action', 'unlockafe_table_reservation_submit');
			formData.append('nonce', $form.find('input[name="unlockafe_reservation_nonce"]').val());

			var adminEmail = $form.data('admin-email');
			var sendCustomer = $form.data('send-customer-email');
			var successMessage = $form.data('success-message');
			if (adminEmail) formData.append('admin_email', adminEmail);
			if (sendCustomer) formData.append('send_customer_email', sendCustomer);
			if (successMessage) formData.append('success_message', successMessage);

			var ajaxUrl = $form.data('ajax-url') || (typeof unlockafeTableReservation !== 'undefined' && unlockafeTableReservation.ajax_url) || (window.unlockafeTableReservation && window.unlockafeTableReservation.ajax_url) || '/wp-admin/admin-ajax.php';
			$.ajax({
				url: ajaxUrl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function (res) {
					if (res.success) {
						$msg.addClass('success').text(res.data.message || 'Thank you! Your table has been reserved.').show();
						if (showSummary && res.data.summary) {
							var s = res.data.summary;
							var html = '<div class="unlockaddons_table_reservation_popup_inner">';
							html += '<h4 class="unlockaddons_table_reservation_popup_title">' + escapeHtml('Booking Summary') + '</h4>';
							if (s.date) html += '<p><strong>Date:</strong> ' + escapeHtml(s.date) + '</p>';
							if (s.time) html += '<p><strong>Time:</strong> ' + escapeHtml(s.time) + '</p>';
							if (s.party_size != null) html += '<p><strong>Total seats / Party size:</strong> ' + escapeHtml(String(s.party_size)) + '</p>';
							if (s.name) html += '<p><strong>Name:</strong> ' + escapeHtml(s.name) + '</p>';
							if (s.location) html += '<p><strong>Location:</strong> ' + escapeHtml(s.location) + '</p>';
							if (s.min_guest != null && s.min_guest > 0) html += '<p><strong>Min guest:</strong> ' + escapeHtml(String(s.min_guest)) + '</p>';
							if (s.max_guest != null && s.max_guest > 0) html += '<p><strong>Max guest:</strong> ' + escapeHtml(String(s.max_guest)) + '</p>';
							if (s.custom && Array.isArray(s.custom)) {
								s.custom.forEach(function (row) {
									html += '<p><strong>' + escapeHtml(row.type || '') + ':</strong> ' + escapeHtml(String(row.qty != null ? row.qty : '')) + '</p>';
								});
							}
							html += '<button type="button" class="unlockaddons_table_reservation_popup_close">' + escapeHtml('Close') + '</button>';
							html += '</div>';
							var $popup = $('<div class="unlockaddons_table_reservation_popup_overlay">').html(html);
							$popup.find('.unlockaddons_table_reservation_popup_close').on('click', function () { $popup.remove(); });
							$popup.on('click', function (ev) { if (ev.target === ev.currentTarget) $popup.remove(); });
							$('body').append($popup);
						}
						$form.find('input, select, textarea').prop('disabled', true);
						if (redirect) {
							setTimeout(function () { window.location.href = redirect; }, 2000);
						}
					} else {
						$msg.addClass('error').text(res.data && res.data.message ? res.data.message : 'Something went wrong. Please try again.').show();
					}
				},
				error: function () {
					$msg.addClass('error').text('Unable to submit. Please try again or contact us.').show();
				}
			});
		});
	}

	function escapeHtml(text) {
		if (text == null) return '';
		var div = document.createElement('div');
		div.textContent = text;
		return div.innerHTML;
	}

	$(function () {
		initTableReservation();
	});

	if (typeof elementorFrontend !== 'undefined') {
		elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-table-reservation.default', function () {
			initTableReservation();
		});
	}
})(jQuery);
