/**
 * Topping Groups JavaScript
 *
 * @package Foodord
 */

(function ($) {
	'use strict';

	const ToppingGroups = {
		init: function () {
			this.createModal();
			this.bindEvents();
		},

	createModal: function () {
		// Create modal HTML
		const modalHtml = `
			<div id="foodord-group-type-modal" class="foodord-modal">
				<div class="foodord-modal__content">
					<button class="foodord-modal__close" type="button">
						<span class="dashicons dashicons-no-alt"></span>
					</button>
					<div class="foodord-modal__header">
						<h2 class="foodord-modal__title">
							<span class="dashicons dashicons-warning"></span>
							Group Type Change
						</h2>
					</div>
					<div class="foodord-modal__body">
						<p class="foodord-modal__message">
							Changing the group type and proceeding to step 2 will reset all topping data you entered (names, prices, default selections).
							<br><br>
							<strong>This action cannot be undone.</strong> Are you sure you want to continue?
						</p>
					</div>
					<div class="foodord-modal__actions">
						<button type="button" class="foodord-modal__button foodord-modal__button--cancel" id="foodord-modal-cancel">
							Cancel
						</button>
						<button type="button" class="foodord-modal__button foodord-modal__button--confirm" id="foodord-modal-confirm">
							Continue
						</button>
					</div>
				</div>
			</div>
		`;

		// Append modal to body
		$('body').append(modalHtml);
	},

	bindEvents: function () {
		// Store initial group type for edit mode warning
		const initialGroupType = $('input[name="group_type"]:checked').val();
		const isEditMode = window.location.search.includes('action=edit');
		let pendingGroupTypeChange = null;
		const toggleSelector = '.group-type-option__toggle-button';

		const syncToggleState = function($button, state) {
			const isActive = !!state;
			$button.attr('aria-pressed', isActive ? 'true' : 'false');
			$button.toggleClass('is-active', isActive);
		};

		$(toggleSelector).each(function() {
			const $button = $(this);
			const hiddenId = $button.data('hiddenInput');
			if (!hiddenId) {
				return;
			}
			const $hidden = $('#' + hiddenId);
			if (!$hidden.length) {
				return;
			}
			const initialState = parseInt($hidden.val(), 10) === 1;
			syncToggleState($button, initialState);
		});

		// Helper function to reset to original selection
		const resetToOriginalSelection = function() {
			$('input[name="group_type"]').prop('checked', false);
			$('.group-type-option').removeClass('selected');
			$('input[name="group_type"][value="' + initialGroupType + '"]').prop('checked', true);
			$('input[name="group_type"][value="' + initialGroupType + '"]').closest('.group-type-option').addClass('selected');
		};

		// Group type change event
		$('input[name="group_type"]').on('change', function (e) {
			const newGroupType = $(this).val();

			// Check if we're in edit mode and user is changing group type
			if (isEditMode && initialGroupType && newGroupType !== initialGroupType) {
				// Prevent the change temporarily
				e.preventDefault();

				// Store the pending change
				pendingGroupTypeChange = $(this);

				// Reset to original selection
				resetToOriginalSelection();

				// Show modal
				$('#foodord-group-type-modal').addClass('is-open');
				return false;
			}

			// Enable Next button when a group type is selected
			if ($(this).is(':checked')) {
				$('#group-type-next').prop('disabled', false);
				// Update visual state
				$('.group-type-option').removeClass('selected');
				$(this).closest('.group-type-option').addClass('selected');
			}
		});

		// Modal events
		$(document).on('click', '#foodord-modal-cancel, .foodord-modal__close', function () {
			resetToOriginalSelection();
			$('#foodord-group-type-modal').removeClass('is-open');
			pendingGroupTypeChange = null;
		});

		$(document).on('click', '#foodord-modal-confirm', function () {
			if (pendingGroupTypeChange) {
				// Apply the pending change without triggering the warning again
				pendingGroupTypeChange.prop('checked', true);

				// Enable Next button
				$('#group-type-next').prop('disabled', false);
				// Update visual state
				$('.group-type-option').removeClass('selected');
				pendingGroupTypeChange.closest('.group-type-option').addClass('selected');

				pendingGroupTypeChange = null;
			}
			$('#foodord-group-type-modal').removeClass('is-open');
		});

		// Close modal on backdrop click
		$(document).on('click', '.foodord-modal', function (e) {
			if (e.target === this) {
				resetToOriginalSelection();
				$(this).removeClass('is-open');
				pendingGroupTypeChange = null;
			}
		});

		// Escape key to close modal
		$(document).on('keydown', function (e) {
			if (e.key === 'Escape' && $('#foodord-group-type-modal').hasClass('is-open')) {
				resetToOriginalSelection();
				$('#foodord-group-type-modal').removeClass('is-open');
				pendingGroupTypeChange = null;
			}
		});

		// Check if a radio is already selected on page load
		if ($('input[name="group_type"]:checked').length > 0) {
			$('#group-type-next').prop('disabled', false);
		}

		$(document).on('click', toggleSelector, function (event) {
			event.preventDefault();
			const $button = $(this);
			const hiddenId = $button.data('hiddenInput');
			if (!hiddenId) {
				return;
			}
			const $hidden = $('#' + hiddenId);
			if (!$hidden.length) {
				return;
			}
			const isActive = $button.attr('aria-pressed') === 'true';
			const newState = !isActive;
			$hidden.val(newState ? '1' : '0');
			syncToggleState($button, newState);
		});
	}
	};

	$(document).ready(function () {
		ToppingGroups.init();

		// Auto hide only success notices after saving (after 5 seconds)
		const $successNotice = $('.notice.notice-success.is-dismissible');
		if ($successNotice.length > 0) {
			setTimeout(function() {
				$successNotice.fadeOut(500, function() {
					$(this).remove();
				});
			}, 5000);
		}
	});

})(jQuery);
