/**
 * Page Access Control Admin JavaScript
 *
 * Handles dynamic rule management and UI interactions
 */
(function($) {
	'use strict';

	$(document).ready(function() {
		const pageAccessAdmin = {
			/**
			 * Initialize
			 */
			init: function() {
				this.bindEvents();
				this.initializeState();
			},

			/**
			 * Bind event handlers
			 */
			bindEvents: function() {
				// Page selection
				$('.kcm-page-toggle').on('change', this.handlePageToggle);
				$('.kcm-page-item').on('click', this.handlePageClick);

				// Access type change
				$(document).on('change', '.kcm-access-type-select', this.handleAccessTypeChange);

				// Rule management
				$(document).on('click', '.kcm-add-rule', this.handleAddRule);
				$(document).on('click', '.kcm-remove-rule', this.handleRemoveRule);
				$(document).on('change', '.kcm-rule-type', this.handleRuleTypeChange);

				// Rule value change
				$(document).on('change', '.kcm-rule-value', this.handleRuleValueChange);

				// Form submission validation
				$('#kcm-page-access-form').on('submit', this.handleFormSubmit);
			},

			/**
			 * Initialize state based on current data
			 */
			initializeState: function() {
				// Show first protected page if any
				const firstProtected = $('.kcm-page-item.is-protected').first();
				if (firstProtected.length) {
					this.showPageConfig(firstProtected.data('page-id'));
				}
			},

			/**
			 * Show the unsaved changes reminder banner
			 */
			markUnsaved: function() {
				var $notice = $('.kcm-unsaved-notice');
				if ($notice.length && !$notice.is(':visible')) {
					$notice.slideDown();
				}
			},

			/**
			 * Handle page checkbox toggle
			 */
			handlePageToggle: function(e) {
				e.stopPropagation();
				const pageItem = $(this).closest('.kcm-page-item');
				const pageId = pageItem.data('page-id');

				if ($(this).is(':checked')) {
					pageItem.addClass('is-protected');
					// Update status based on current access type
					pageAccessAdmin.updatePageStatus(pageId);
					// Automatically show config when page is checked
					pageAccessAdmin.showPageConfig(pageId);
				} else {
					pageItem.removeClass('is-protected');
					pageItem.find('.kcm-page-status').text('').removeClass('kcm-status-login kcm-status-custom');
					pageAccessAdmin.hidePageConfig(pageId);
				}

				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Handle page item click
			 */
			handlePageClick: function(e) {
				if ($(e.target).is('input[type="checkbox"]')) {
					return;
				}

				const pageId = $(this).data('page-id');
				const isProtected = $(this).hasClass('is-protected');

				if (isProtected) {
					// Show config for this page
					pageAccessAdmin.showPageConfig(pageId);
				}
			},

			/**
			 * Show page configuration panel
			 */
			showPageConfig: function(pageId) {
				// Hide all configs
				$('.kcm-page-config-panel').hide();
				$('.kcm-no-page-selected').hide();

				// Highlight selected page
				$('.kcm-page-item').removeClass('selected');
				$('.kcm-page-item[data-page-id="' + pageId + '"]').addClass('selected');

				// Show config for this page
				$('.kcm-page-config-panel[data-page-id="' + pageId + '"]').show();
			},

			/**
			 * Hide page configuration panel
			 */
			hidePageConfig: function(pageId) {
				$('.kcm-page-config-panel[data-page-id="' + pageId + '"]').hide();
				$('.kcm-page-item[data-page-id="' + pageId + '"]').removeClass('selected');

				// Show no-page-selected message if no pages are protected
				if ($('.kcm-page-item.is-protected').length === 0) {
					$('.kcm-no-page-selected').show();
				} else {
					// Show first protected page
					const firstProtected = $('.kcm-page-item.is-protected').first();
					if (firstProtected.length) {
						pageAccessAdmin.showPageConfig(firstProtected.data('page-id'));
					}
				}
			},

			/**
			 * Handle access type change
			 */
			handleAccessTypeChange: function() {
				const accessType = $(this).val();
				const panel = $(this).closest('.kcm-page-config-panel');
				const pageId = panel.data('page-id');
				const customRules = panel.find('.kcm-custom-rules');

				if (accessType === 'custom') {
					customRules.slideDown();
				} else {
					customRules.slideUp();
				}

				// Update status in left panel
				pageAccessAdmin.updatePageStatus(pageId, accessType);
				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Update page status badge in left panel
			 */
			updatePageStatus: function(pageId, accessType) {
				const pageItem = $('.kcm-page-item[data-page-id="' + pageId + '"]');
				const statusSpan = pageItem.find('.kcm-page-status');

				// If accessType not provided, get it from the select dropdown
				if (!accessType) {
					accessType = $('.kcm-page-config-panel[data-page-id="' + pageId + '"] .kcm-access-type-select').val();
				}

				// Update data attribute
				pageItem.attr('data-access-type', accessType);

				// Update status text and class
				statusSpan.removeClass('kcm-status-login kcm-status-custom');
				if (accessType === 'custom') {
					statusSpan.text('Custom Rules').addClass('kcm-status-custom');
				} else {
					statusSpan.text('Login Required').addClass('kcm-status-login');
				}
			},

			/**
			 * Handle add rule button click
			 */
			handleAddRule: function(e) {
				e.preventDefault();
				const pageId = $(this).data('page-id');
				const container = $('.kcm-rules-container[data-page-id="' + pageId + '"]');

				// Add OR separator to last rule if exists
				const lastRule = container.find('.kcm-rule-item').last();
				if (lastRule.length && !lastRule.find('.kcm-rule-separator').length) {
					lastRule.append('<div class="kcm-rule-separator">OR</div>');
				}

				// Create new rule
				const newRule = pageAccessAdmin.createRuleElement(pageId, 'user', '');
				container.append(newRule);
				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Handle remove rule button click
			 */
			handleRemoveRule: function(e) {
				e.preventDefault();
				const ruleItem = $(this).closest('.kcm-rule-item');
				const container = ruleItem.closest('.kcm-rules-container');
				const pageId = container.data('page-id');

				// Remove the rule
				ruleItem.remove();

				// If no rules left, switch to Login Required
				if (container.find('.kcm-rule-item').length === 0) {
					const panel = container.closest('.kcm-page-config-panel');

					// Switch access type to Login Required
					panel.find('.kcm-access-type-select').val('login_required');
					panel.find('.kcm-custom-rules').slideUp();

					// Update status badge in left panel
					pageAccessAdmin.updatePageStatus(pageId, 'login_required');
				} else {
					// Remove trailing OR separator from last rule
					const lastRule = container.find('.kcm-rule-item').last();
					if (lastRule.length) {
						lastRule.find('.kcm-rule-separator').remove();
					}
				}

				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Handle rule type change
			 */
			handleRuleTypeChange: function() {
				const ruleType = $(this).val();
				const ruleItem = $(this).closest('.kcm-rule-item');
				const valueSelect = ruleItem.find('.kcm-rule-value');

				// Update value dropdown based on type
				pageAccessAdmin.updateValueOptions(valueSelect, ruleType);
				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Handle rule value change
			 */
			handleRuleValueChange: function() {
				pageAccessAdmin.markUnsaved();
			},

			/**
			 * Create a new rule element
			 */
			createRuleElement: function(pageId, ruleType, ruleValue) {
				const ruleTypeLabels = window.macmPageAccess.ruleTypeLabels;

				const html = $('<div class="kcm-rule-item">' +
					'<div class="kcm-rule-fields">' +
						'<select name="rule_type[' + pageId + '][]" class="kcm-rule-type">' +
							'<option value="user">' + ruleTypeLabels.user + '</option>' +
							'<option value="membership_type">' + ruleTypeLabels.membership_type + '</option>' +
							'<option value="group">' + ruleTypeLabels.group + '</option>' +
						'</select>' +
						'<select name="rule_value[' + pageId + '][]" class="kcm-rule-value"></select>' +
						'<button type="button" class="button kcm-remove-rule">Remove</button>' +
					'</div>' +
				'</div>');

				// Set selected rule type
				html.find('.kcm-rule-type').val(ruleType);

				// Populate value options
				const valueSelect = html.find('.kcm-rule-value');
				pageAccessAdmin.updateValueOptions(valueSelect, ruleType, ruleValue);

				return html;
			},

			/**
			 * Update value dropdown options based on rule type
			 */
			updateValueOptions: function(selectElement, ruleType, selectedValue) {
				const data = window.macmPageAccess;
				let options = '';

				switch (ruleType) {
					case 'user':
						$.each(data.users, function(id, name) {
							options += '<option value="' + id + '">' + name + '</option>';
						});
						break;

					case 'membership_type':
						$.each(data.membershipTypes, function(id, name) {
							options += '<option value="' + id + '">' + name + '</option>';
						});
						break;

					case 'group':
						$.each(data.groups, function(id, name) {
							options += '<option value="' + id + '">' + name + '</option>';
						});
						break;
				}

				selectElement.html(options);

				if (selectedValue) {
					selectElement.val(selectedValue);
				}
			},

			/**
			 * Handle form submission
			 */
			handleFormSubmit: function(e) {
				// Validate that custom access types have at least one rule
				let valid = true;
				$('.kcm-page-config-panel').each(function() {
					const pageId = $(this).data('page-id');
					const isProtected = $('input[name="protected_pages[]"][value="' + pageId + '"]').is(':checked');

					if (!isProtected) {
						return;
					}

					const accessType = $(this).find('.kcm-access-type-select').val();
					if (accessType === 'custom') {
						const rulesContainer = $(this).find('.kcm-rules-container');
						const ruleCount = rulesContainer.find('.kcm-rule-item').length;

						if (ruleCount === 0) {
							alert('Please add at least one rule for pages with custom access type.');
							valid = false;
							return false;
						}
					}
				});

				return valid;
			}
		};

		// Initialize
		pageAccessAdmin.init();
	});
})(jQuery);
