/**
 * Toppings Step Navigation Master Controller
 *
 * @package Foodord
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		const urlParams = new URLSearchParams(window.location.search);
		const initialStep = parseInt(urlParams.get('step'), 10) || 1;
		const defaultGroupType = $('input[name="group_type"]:checked').val() || 'dropdown';
		const initialGroupType = urlParams.get('group_type') || defaultGroupType;

		window.foodordCurrentGroupType = initialGroupType;

		setGroupTypeSelection(initialGroupType);
		switchToStep(initialStep, {
			groupType: initialGroupType,
			skipUrlUpdate: true,
		});

		$('input[name="group_type"]').on('change', function() {
			const selectedType = $(this).val();
			window.foodordCurrentGroupType = selectedType;
			setGroupTypeSelection(selectedType);
			$('#group-type-next').prop('disabled', false);
		});

		$('.foodord-steps-indicator .step').on('click', function() {
			const $this = $(this);
			const stepNumber = $this.data('step');

			if ($this.hasClass('completed')) {
				switchToStep(stepNumber, {
					groupType: window.foodordCurrentGroupType,
				});
			}
		});

		$(document).on('click', '#group-type-next:not(:disabled)', function(event) {
			event.preventDefault();

			const selectedType = $('input[name="group_type"]:checked').val();
			if (selectedType) {
				switchToStep(2, {
					groupType: selectedType,
				});
			}

			return false;
		});

		$(document).on('click', '#topping-items-back', function(event) {
			event.preventDefault();
			switchToStep(1, {
				groupType: window.foodordCurrentGroupType,
			});
			return false;
		});
	});

	function highlightSelectedGroupType() {
		$('.group-type-option').removeClass('selected');
		$('input[name="group_type"]:checked').each(function() {
			$(this).closest('.group-type-option').addClass('selected');
		});
	}

	function switchToStep(stepNumber, options = {}) {
		const targetStep = Math.min(Math.max(stepNumber, 1), 2);
		const groupType = options.groupType || window.foodordCurrentGroupType || $('input[name="group_type"]:checked').val() || 'dropdown';
		const shouldUpdateUrl = !options.skipUrlUpdate;

		$('.foodord-step-container').addClass('step-content--hidden');
		$('#step-' + targetStep + '-container').removeClass('step-content--hidden');

		$('.foodord-steps-indicator .step').each(function() {
			const $step = $(this);
			const currentStepNum = $step.data('step');

			if (currentStepNum < targetStep) {
				$step.removeClass('active').addClass('completed');
			} else if (currentStepNum === targetStep) {
				$step.removeClass('completed').addClass('active');
			} else {
				$step.removeClass('completed active');
			}
		});

		if (targetStep === 2) {
			setGroupTypeSelection(groupType);
			activateGroupTypePanel(groupType);
			if (shouldUpdateUrl) {
				updateURLStep(targetStep, groupType);
			}
		} else {
			if (shouldUpdateUrl) {
				updateURLStep(targetStep);
			}
			setGroupTypeSelection(groupType);
		}

		toggleSaveButton(targetStep);
	}

	function toggleSaveButton(stepNumber) {
		if (stepNumber === 2) {
			$('.wrc-save-fixed').show();
		} else {
			$('.wrc-save-fixed').hide();
		}
	}

	function updateURLStep(stepNumber, groupType) {
		const url = new URL(window.location);
		url.searchParams.set('step', stepNumber);

		if (stepNumber === 2 && groupType) {
			url.searchParams.set('group_type', groupType);
		} else {
			url.searchParams.delete('group_type');
		}

		window.history.replaceState({}, '', url);
	}

	function activateGroupTypePanel(groupType) {
		const fallbackType = $('input[name="group_type"]:checked').val() || 'dropdown';
		const resolvedType = groupType || window.foodordCurrentGroupType || fallbackType;
		let $activePanel = $();

		$('.topping-items-panel').each(function() {
			const $panel = $(this);
			const panelType = $panel.data('group-type');
			const isActive = panelType === resolvedType;

			$panel.toggleClass('step-content--hidden', !isActive).attr('aria-hidden', isActive ? 'false' : 'true');
		$panel.find('input, select, textarea').prop('disabled', !isActive);
			$panel.find('.add-new-topping, .remove-topping-item').prop('disabled', !isActive);

			if (isActive) {
				$activePanel = $panel;
			}
		});

		window.foodordCurrentGroupType = resolvedType;
		$('.topping-items-content').attr('data-active-group-type', resolvedType);
		$('#selected_group_type').val(resolvedType);

		$(document).trigger('foodord:toppingsGroupTypeActivated', [resolvedType, $activePanel]);

		return $activePanel;
	}

function setGroupTypeSelection(groupType, options = {}) {
	if (!groupType) {
		return;
	}

	const $radio = $('input[name="group_type"][value="' + groupType + '"]');
	if ($radio.length) {
		$radio.prop('checked', true);
	}

	if (!options.skipHighlight) {
		highlightSelectedGroupType();
	}
}

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

})(jQuery);
