/**
 * Event Genius - Registration Types Admin (inline panel)
 * Add, toggle, remove registration type cards; sync deleted IDs for save.
 */
(function($) {
	'use strict';

	var RegistrationTypesAdmin = {
		registrationTypeTemplateHtml: null,

		init: function() {
			this.registrationTypeTemplateHtml = this.getRegistrationTypeTemplateHtml();
			this.bindEvents();
			this.initSortable();
			$('.evge-registration-type-item').addClass('evge-collapsed');
			this.syncCapacityInputs();
			this.updateRemoveButtonsState();
			$('.evge-registration-type-item').each(function() {
				var $item = $(this);
				// use_event_window: enabled = inherit event window (timeline hidden); disabled = custom window (show matching open/close subs on load).
				if ($item.find('.evge-restrict-availability-wrap .evge-toggle-setting-enabled').val() === 'disabled') {
					RegistrationTypesAdmin.processRegTypeTimelineInItem($item);
				}
			});
		},

		initSortable: function() {
			var $list = $('#evge-registration-types-list');
			if (!$list.length) return;
			var self = this;
			$list.sortable({
				items: '.evge-registration-type-item',
				handle: '.evge-drag-handle',
				axis: 'y',
				placeholder: 'evge-sortable-placeholder',
				cursor: 'move',
				opacity: 0.8,
				start: function(event, ui) {
					ui.placeholder.height(ui.item.outerHeight() - 1);
				},
				over: function(event, ui) {
					ui.placeholder.height(ui.helper.outerHeight() - 1);
				},
				update: function() {
					self.resetIndexes();
					self.updateRemoveButtonsState();
				}
			});
		},

		bindEvents: function() {
			$(document).on('click', '#evge-add-registration-type', this.addRegistrationType.bind(this));
			$(document).on('click', '.evge-remove-registration-type', this.removeRegistrationType.bind(this));
			$(document).on('click', '.evge-registration-type-start-from-scratch', this.dismissAddChoices.bind(this));
			$(document).on('click', '.evge-registration-type-show-template-dropdown', this.showTemplateDropdown.bind(this));
			$(document).on('click', '.evge-registration-type-template-cancel', this.dismissAddChoices.bind(this));
			$(document).on('change', '.evge-registration-type-template-select', this.applyTemplateToCard.bind(this));
			$(document).on('click', '.evge-registration-type-toggle', this.toggleCollapsed.bind(this));
			$(document).on('click', '.evge-reg-type-unlimited-wrap .evge-settings-toggle-wrap', this.syncCapacityInputAfterToggle.bind(this));
			$(document).on('click', '.evge-reg-type-use-event-price-wrap .evge-settings-toggle-wrap', this.toggleUseEventPrice.bind(this));
			$(document).on('click', '.evge-reg-type-use-event-capacity-wrap .evge-settings-toggle-wrap', this.toggleUseEventCapacity.bind(this));
			$(document).on('click', '.evge-restrict-availability-wrap .evge-settings-toggle-wrap', this.toggleAvailabilityTimeline.bind(this));
			$(document).on('change', '.evge-reg-type-open-type, .evge-reg-type-close-type', this.processRegTypeTimelineSelection.bind(this));
			$(document).on('change', '.evge-reg-type-status-select', this.onStatusChange.bind(this));
			$(document).on('input', '.evge-registration-type-name-input', this.updateSummary.bind(this));
			$(document).on('input', '.evge-price-amount-input', this.updateSummary.bind(this));
		},

		onStatusChange: function(e) {
			var $select = $(e.currentTarget);
			if ($select.val() !== 'disabled') return;
			var activeCount = 0;
			$('#evge-registration-types-list').find('.evge-reg-type-status-select').each(function() {
				if ($(this).val() === 'active') activeCount++;
			});
			if (activeCount === 0) {
				$select.val('active');
				alert(evgeRegistrationTypesL10n.lastEnabledRequired || 'At least one active registration type is required.');
			}
			this.updateRemoveButtonsState();
		},

		getRegistrationTypeTemplateHtml: function() {
			var $tpl = $('#evge-registration-type-template');
			if ($tpl.length) {
				var html = $tpl.html();
				$tpl.remove();
				if (html && typeof html.trim === 'function') {
					html = html.trim();
				}
				if (html) {
					return html;
				}
			}
			return null;
		},

		addRegistrationType: function(e) {
			e.preventDefault();
			var $container = $('#evge-registration-types-list');
			var html = this.registrationTypeTemplateHtml;
			console.log(html);
			if (!html) return;
			var index = $container.find('.evge-registration-type-item').length;
			html = html.replace(/INDEX_PLACEHOLDER/g, index);
			$container.find('.evge-no-registration-types').remove();
			$container.append(html);
			if ($container.hasClass('ui-sortable')) {
				$container.sortable('refresh');
			}
			var $newItem = $container.find('.evge-registration-type-item').last();
			$newItem.removeClass('evge-collapsed');
			if ($newItem[0]) $newItem[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
			this.syncCapacityInputs();
			this.processRegTypeTimelineInItem($newItem);
			this.updateRemoveButtonsState();

			var templates = (window.evgeRegistrationTypesL10n && window.evgeRegistrationTypesL10n.templates) ? window.evgeRegistrationTypesL10n.templates : [];
			if (templates.length > 0) {
				var L10n = window.evgeRegistrationTypesL10n || {};
				var choiceHtml = '<div class="evge-registration-type-add-choices">';
				choiceHtml += '<button type="button" class="button-link evge-registration-type-start-from-scratch">' + (L10n.startFromScratch || 'Start from scratch') + '</button>';
				choiceHtml += ' <span class="evge-add-choices-sep">|</span> ';
				choiceHtml += '<button type="button" class="button-link evge-registration-type-show-template-dropdown">' + (L10n.addFromTemplate || 'Add from template') + '</button>';
				choiceHtml += '</div>';
				var $fields = $newItem.find('.evge-registration-type-fields');
				$fields.prepend(choiceHtml);
				$fields.children().not('.evge-registration-type-add-choices').hide();
			}
		},

		showFormFieldsAndRemoveChoices: function($choices) {
			var $card = $choices.closest('.evge-registration-type-item');
			$card.find('.evge-registration-type-fields').children().not('.evge-registration-type-add-choices').show();
			$choices.remove();
		},

		dismissAddChoices: function(e) {
			e.preventDefault();
			var $choices = $(e.currentTarget).closest('.evge-registration-type-add-choices');
			this.showFormFieldsAndRemoveChoices($choices);
		},

		showTemplateDropdown: function(e) {
			e.preventDefault();
			var $choices = $(e.currentTarget).closest('.evge-registration-type-add-choices');
			var templates = (window.evgeRegistrationTypesL10n && window.evgeRegistrationTypesL10n.templates) ? window.evgeRegistrationTypesL10n.templates : [];
			var L10n = window.evgeRegistrationTypesL10n || {};
			var chooseLabel = L10n.chooseTemplate || 'Choose a template…';
			var cancelLabel = L10n.cancel || 'Cancel';
			var html = '<select class="evge-registration-type-template-select" aria-label="' + chooseLabel.replace(/"/g, '&quot;') + '">';
			html += '<option value="">' + chooseLabel + '</option>';
			for (var i = 0; i < templates.length; i++) {
				var t = templates[i];
				var name = (t.name || '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;');
				html += '<option value="' + (t.id || '') + '">' + name + '</option>';
			}
			html += '</select>';
			html += ' <button type="button" class="button-link evge-registration-type-template-cancel">' + cancelLabel + '</button>';
			$choices.html(html);
		},

		applyTemplateToCard: function(e) {
			var $select = $(e.currentTarget);
			var templateId = $select.val();
			if (!templateId) return;
			var templates = (window.evgeRegistrationTypesL10n && window.evgeRegistrationTypesL10n.templates) ? window.evgeRegistrationTypesL10n.templates : [];
			var template = null;
			for (var i = 0; i < templates.length; i++) {
				if (String(templates[i].id) === String(templateId)) {
					template = templates[i];
					break;
				}
			}
			if (!template) return;
			var $choices = $select.closest('.evge-registration-type-add-choices');
			var $card = $choices.closest('.evge-registration-type-item');
			$card.find('.evge-registration-type-name-input').val(template.name || '');
			$card.find('.evge-registration-type-fields textarea').first().val(template.description || '');
			this.updateSummary({ currentTarget: $card.find('.evge-registration-type-name-input')[0] });
			this.showFormFieldsAndRemoveChoices($choices);
		},

		removeRegistrationType: function(e) {
			e.preventDefault();
			var $target = $(e.currentTarget);
			if ($target.hasClass('evge-reg-type-remove-disabled')) {
				return;
			}
			var $list = $('#evge-registration-types-list');
			var $items = $list.find('.evge-registration-type-item');
			if ($items.length <= 1) {
				return;
			}
			var $item = $target.closest('.evge-registration-type-item');
			var activeCount = 0;
			$items.find('.evge-reg-type-status-select').each(function() {
				if ($(this).val() === 'active') activeCount++;
			});
			if ($item.find('.evge-reg-type-status-select').val() === 'active' && activeCount <= 1) {
				return;
			}
			if (!confirm(evgeRegistrationTypesL10n.confirmRemove)) return;
			var typeId = $item.attr('data-type-id') || '';
			if (typeId && typeId !== '') {
				var $deleted = $('#evge-registration-types-deleted-container');
				$deleted.append('<input type="hidden" name="evge_registration_types_deleted[]" value="' + typeId + '">');
			}
			var self = this;
			$item.fadeOut(200, function() {
				$(this).remove();
				RegistrationTypesAdmin.resetIndexes();
				if ($list.find('.evge-registration-type-item').length === 0) {
					$list.prepend('<p class="evge-no-registration-types evge-inline-list-empty-state">' + evgeRegistrationTypesL10n.noTypes + '</p>');
				}
				self.updateRemoveButtonsState();
			});
		},

		updateRemoveButtonsState: function() {
			var $list = $('#evge-registration-types-list');
			var $items = $list.find('.evge-registration-type-item');
			var isLastOnly = $items.length <= 1;
			var activeCount = 0;
			$items.find('.evge-reg-type-status-select').each(function() {
				if ($(this).val() === 'active') activeCount++;
			});
			var msgLastType = evgeRegistrationTypesL10n.lastTypeRequired || 'At least one registration type is required.';
			var msgLastActive = evgeRegistrationTypesL10n.lastEnabledRequired || 'At least one active registration type is required.';
			$items.each(function() {
				var $card = $(this);
				var $btn = $card.find('.evge-remove-registration-type');
				var isActive = $card.find('.evge-reg-type-status-select').val() === 'active';
				var isOnlyActive = isActive && activeCount <= 1;
				var shouldDisable = isLastOnly || isOnlyActive;
				var title = shouldDisable ? (isLastOnly ? msgLastType : msgLastActive) : (evgeRegistrationTypesL10n.removeLabel || '');
				if (!shouldDisable) {
					$btn.removeClass('evge-reg-type-remove-disabled').removeAttr('aria-disabled').attr('title', title);
				} else {
					$btn.addClass('evge-reg-type-remove-disabled').attr('aria-disabled', 'true').attr('title', title);
				}
			});
		},

		toggleCollapsed: function(e) {
			e.preventDefault();
			$(e.currentTarget).closest('.evge-registration-type-item').toggleClass('evge-collapsed');
		},

		syncCapacityInputs: function() {
			$('.evge-registration-type-item').each(function() {
				var $item = $(this);
				var enabled = $item.find('.evge-reg-type-unlimited-wrap .evge-toggle-setting-enabled').val() === 'enabled';
				$item.find('.evge-reg-type-capacity-input').prop('disabled', enabled);
			});
		},
		syncCapacityInputAfterToggle: function(e) {
			var $item = $(e.currentTarget).closest('.evge-registration-type-item');
			setTimeout(function() {
				var enabled = $item.find('.evge-reg-type-unlimited-wrap .evge-toggle-setting-enabled').val() === 'enabled';
				$item.find('.evge-reg-type-capacity-input').prop('disabled', enabled);
			}, 50);
		},
		toggleUseEventPrice: function(e) {
			var $item = $(e.currentTarget).closest('.evge-registration-type-item');
			setTimeout(function() {
				var useEvent = $item.find('.evge-reg-type-use-event-price-wrap .evge-toggle-setting-enabled').val() === 'enabled';
				$item.find('.evge-field-price .evge-reg-type-price-custom-wrap').toggle(!useEvent);
				$item.find('.evge-field-price .evge-reg-type-use-event-hint').toggle(useEvent);
				$item.find('.evge-registration-type-name-input').trigger('input');
			}, 50);
		},
		toggleUseEventCapacity: function(e) {
			var $item = $(e.currentTarget).closest('.evge-registration-type-item');
			setTimeout(function() {
				var useEvent = $item.find('.evge-reg-type-use-event-capacity-wrap .evge-toggle-setting-enabled').val() === 'enabled';
				$item.find('.evge-field-capacity .evge-reg-type-capacity-custom-wrap').toggle(!useEvent);
				$item.find('.evge-field-capacity .evge-reg-type-use-event-hint').toggle(useEvent);
				$item.find('.evge-registration-type-name-input').trigger('input');
			}, 50);
		},
		toggleAvailabilityTimeline: function(e) {
			var $item = $(e.currentTarget).closest('.evge-registration-type-item');
			var self = this;
			setTimeout(function() {
				var useEventWindow = $item.find('.evge-restrict-availability-wrap .evge-toggle-setting-enabled').val() === 'enabled';
				$item.find('.evge-reg-type-timeline-wrap').toggle(!useEventWindow);
				if (!useEventWindow) {
					self.processRegTypeTimelineInItem($item);
				}
			}, 50);
		},
		processRegTypeTimelineSelection: function(e) {
			this.processRegTypeTimelineInItem($(e.currentTarget).closest('.evge-registration-type-item'));
		},
		processRegTypeTimelineInItem: function($item) {
			var openType = $item.find('.evge-reg-type-open-type').val();
			var closeType = $item.find('.evge-reg-type-close-type').val();
			$item.find('.evge-reg-type-open-sub').each(function() {
				$(this).toggle($(this).attr('data-type') === openType);
			});
			$item.find('.evge-reg-type-close-sub').each(function() {
				$(this).toggle($(this).attr('data-type') === closeType);
			});
		},

		updateSummary: function(e) {
			var $item = $(e.currentTarget).closest('.evge-registration-type-item');
			var name = $item.find('.evge-registration-type-name-input').val() || evgeRegistrationTypesL10n.newType;
			var price = $item.find('.evge-price-amount-input').val();
			var $notice = $item.find('.evge-registration-type-sold-notice');
			var sold = $notice.length ? ($notice.text().replace(/\D/g, '') || '0') : '0';
			var cap = $item.find('input[name*="[capacity]"]').val();
			var useEventPrice = $item.find('.evge-reg-type-use-event-price-wrap .evge-toggle-setting-enabled').val() === 'enabled';
			var useEventCapacity = $item.find('.evge-reg-type-use-event-capacity-wrap .evge-toggle-setting-enabled').val() === 'enabled';
			var part = useEventPrice ? '' : ((price === '' || price === undefined || parseFloat(price) === 0) ? evgeRegistrationTypesL10n.free : price);
			var soldCap = useEventCapacity ? (sold + ' ' + evgeRegistrationTypesL10n.sold) : ((cap !== undefined && cap !== '') ? (sold + ' / ' + cap) : (sold + ' ' + evgeRegistrationTypesL10n.sold));
			var summary = part ? (name + ' · ' + part + ' · ' + soldCap) : (name + ' · ' + soldCap);
			$item.find('.evge-registration-type-summary').text(summary);
		},

		resetIndexes: function() {
			$('#evge-registration-types-list').find('.evge-registration-type-item').each(function(index) {
				var $item = $(this);
				$item.attr('data-index', index);
				$item.find('[name^="evge_registration_types["]').each(function() {
					var name = $(this).attr('name');
					if (name) {
						var newName = name.replace(/evge_registration_types\[\d+\]/, 'evge_registration_types[' + index + ']');
						$(this).attr('name', newName);
					}
				});
			});
		}
	};

	$(function() {
		if ($('#evge-registration-types-panel').length) {
			RegistrationTypesAdmin.init();
		}
	});
})(jQuery);
