/**
 * Martial Arts Club Manager - Admin Scripts
 *
 * @package KarateClubManager
 */

(function($) {
	'use strict';

	/**
	 * i18n helper — returns translated string from macmAdmin.i18n or falls back to English.
	 *
	 * @param {string} key      The i18n key defined in wp_localize_script().
	 * @param {string} fallback English fallback string.
	 * @return {string}
	 */
	function i18n(key, fallback) {
		return (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n[key]) ? macmAdmin.i18n[key] : fallback;
	}

	/**
	 * Initialize when document is ready
	 */
	$(document).ready(function() {
		KCM_Admin.init();
	});

	/**
	 * Main admin object
	 */
	var KCM_Admin = {
		/**
		 * Initialize admin functionality
		 */
		init: function() {
			this.initArchiveButtons();
			this.initLicenseValidation();
			this.initLicenseExpirationClearButton();
			this.initBeltHistoryButtons();
			this.initBulkArchive();
			this.initSelectAllMembers();
		},

		/**
		 * Initialize Archive/Activate buttons
		 */
		initArchiveButtons: function() {
			var self = this;

			// Handle Archive button click
			$(document).on('click', '.kcm-admin-archive-member', function(e) {
				e.preventDefault();
				var button = $(this);
				var memberId = button.data('member-id');

				if (!confirm(i18n('confirmArchiveMember', 'Are you sure you want to archive this member?'))) {
					return;
				}

				self.toggleMemberStatus(memberId, button);
			});

			// Handle Activate button click
			$(document).on('click', '.kcm-admin-activate-member', function(e) {
				e.preventDefault();
				var button = $(this);
				var memberId = button.data('member-id');

				if (!confirm(i18n('confirmActivateMember', 'Are you sure you want to activate this member?'))) {
					return;
				}

				self.toggleMemberStatus(memberId, button);
			});
		},

		/**
		 * Initialize bulk archive with modal confirmation
		 */
		initBulkArchive: function() {
			var self = this;
			var $form = $('#macm-members-bulk-form');

			if (!$form.length) {
				return;
			}

			// Store the pending action
			self.pendingBulkAction = null;

			// Intercept form submission when archive/activate action selected
			$form.on('submit', function(e) {
				var action = $('#bulk-action-selector-top').val() || $('#bulk-action-selector-bottom').val();

				// Allow non-bulk actions to pass through
				if (action !== 'archive' && action !== 'activate') {
					return true;
				}

				var checkedCount = $('input[name="member_ids[]"]:checked').length;

				if (checkedCount === 0) {
					var noSelectionMsg = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.noMembersSelected)
						? macmAdmin.i18n.noMembersSelected
						: 'Please select at least one member.';
					alert(noSelectionMsg);
					e.preventDefault();
					return false;
				}

				// Show confirmation modal
				e.preventDefault();
				self.pendingBulkAction = action;
				self.showBulkActionModal(action, checkedCount);
				return false;
			});

			// Modal confirm button
			$('#macm-bulk-archive-confirm').on('click', function() {
				$('#macm-bulk-archive-modal').fadeOut(200);
				// Unbind the submit handler and submit
				$form.off('submit').submit();
			});

			// Modal cancel button
			$('#macm-bulk-archive-cancel, #macm-bulk-archive-modal .kcm-modal-close').on('click', function() {
				$('#macm-bulk-archive-modal').fadeOut(200);
				self.pendingBulkAction = null;
			});

			// Close on overlay click
			$('#macm-bulk-archive-modal').on('click', function(e) {
				if (e.target === this) {
					$(this).fadeOut(200);
					self.pendingBulkAction = null;
				}
			});

			// Close on Escape key
			$(document).on('keydown', function(e) {
				if (e.key === 'Escape' && $('#macm-bulk-archive-modal').is(':visible')) {
					$('#macm-bulk-archive-modal').fadeOut(200);
					self.pendingBulkAction = null;
				}
			});
		},

		/**
		 * Initialize select all members checkbox
		 */
		initSelectAllMembers: function() {
			// Handle "Select All" checkbox click in header
			$(document).on('click', '#macm-select-all-members', function() {
				var isChecked = $(this).prop('checked');
				$('input[name="member_ids[]"]').prop('checked', isChecked);
			});

			// Update "Select All" checkbox state when individual checkboxes change
			$(document).on('change', 'input[name="member_ids[]"]', function() {
				var totalCheckboxes = $('input[name="member_ids[]"]').length;
				var checkedCheckboxes = $('input[name="member_ids[]"]:checked').length;
				$('#macm-select-all-members').prop('checked', totalCheckboxes === checkedCheckboxes && totalCheckboxes > 0);
			});
		},

		/**
		 * Show bulk action confirmation modal
		 */
		showBulkActionModal: function(action, count) {
			var message;
			var title;

			if (action === 'archive') {
				title = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.confirmArchive)
					? macmAdmin.i18n.confirmArchive
					: 'Confirm Archive';

				if (count === 1) {
					message = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.archiveOneMember)
						? macmAdmin.i18n.archiveOneMember
						: 'Are you sure you want to archive this member?';
				} else {
					var archiveTemplate = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.archiveMultipleMembers)
						? macmAdmin.i18n.archiveMultipleMembers
						: 'Are you sure you want to archive %d members?';
					message = archiveTemplate.replace('%d', count);
				}
			} else { // activate
				title = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.confirmActivate)
					? macmAdmin.i18n.confirmActivate
					: 'Confirm Activate';

				if (count === 1) {
					message = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.activateOneMember)
						? macmAdmin.i18n.activateOneMember
						: 'Are you sure you want to activate this member?';
				} else {
					var activateTemplate = (typeof macmAdmin !== 'undefined' && macmAdmin.i18n && macmAdmin.i18n.activateMultipleMembers)
						? macmAdmin.i18n.activateMultipleMembers
						: 'Are you sure you want to activate %d members?';
					message = activateTemplate.replace('%d', count);
				}
			}

			$('#macm-bulk-modal-title').text(title);
			$('#macm-bulk-archive-message').text(message);
			$('#macm-bulk-archive-modal').fadeIn(200);
		},

		/**
		 * Toggle member status (Archive/Activate)
		 */
		toggleMemberStatus: function(memberId, button) {
			var self = this;

			// Disable button and show loading
			button.prop('disabled', true);
			var originalText = button.text();
			button.text(i18n('processing', 'Processing...'));

			self.ajaxRequest(
				'macm_admin_toggle_member_status',
				{ member_id: memberId },
				function(data) {
					// Success - reload page to show updated status
					location.reload();
				},
				function(data) {
					// Error
					button.prop('disabled', false);
					button.text(originalText);
					alert(data.message || i18n('errorUpdatingStatus', 'Error updating member status'));
				}
			);
		},

		/**
		 * Show loading state
		 */
		showLoading: function(element) {
			$(element).addClass('kcm-loading');
		},

		/**
		 * Hide loading state
		 */
		hideLoading: function(element) {
			$(element).removeClass('kcm-loading');
		},

		/**
		 * Show success notice
		 */
		showSuccess: function(message) {
			this.showNotice(message, 'success');
		},

		/**
		 * Show error notice
		 */
		showError: function(message) {
			this.showNotice(message, 'error');
		},

		/**
		 * Show notice
		 */
		showNotice: function(message, type) {
			var noticeClass = 'kcm-notice kcm-notice-' + type;
			var notice = $('<div class="' + noticeClass + '">' + message + '</div>');

			$('.kcm-admin-wrapper').prepend(notice);

			// Auto-hide after 5 seconds
			setTimeout(function() {
				notice.fadeOut(function() {
					$(this).remove();
				});
			}, 5000);
		},

		/**
		 * Make AJAX request
		 */
		ajaxRequest: function(action, data, successCallback, errorCallback) {
			data.action = action;
			data.nonce = macmAdmin.nonce;

			$.ajax({
				url: macmAdmin.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						if (typeof successCallback === 'function') {
							successCallback(response.data);
						}
					} else {
						if (typeof errorCallback === 'function') {
							errorCallback(response.data);
						}
					}
				},
				error: function(xhr, status, error) {
					if (typeof errorCallback === 'function') {
						errorCallback({message: i18n('ajaxFailed', 'AJAX request failed:') + ' ' + error});
					}
				}
			});
		},

		/**
		 * Initialize license number/expiration validation
		 * Requires license number before allowing expiration date
		 */
		initLicenseValidation: function() {
			var self = this;

			// Function to update expiration field state
			function updateExpirationField(licenseInput, expirationInput) {
				var hasLicenseNumber = licenseInput.val().trim().length > 0;

				if (hasLicenseNumber) {
					expirationInput.prop('disabled', false);
					expirationInput.closest('.kcm-form-row').find('.kcm-license-note').remove();
				} else {
					expirationInput.prop('disabled', true);
					expirationInput.val(''); // Clear any existing value

					// Add note if not already present
					if (expirationInput.closest('.kcm-form-row').find('.kcm-license-note').length === 0) {
						expirationInput.closest('.kcm-form-row').append(
							'<p class="kcm-license-note" style="color: #d63638; font-size: 12px; margin-top: 5px;">' +
							i18n('licenseNumberRequired', 'Please enter a License Number first before setting the expiration date.') +
							'</p>'
						);
					}
				}
			}

			// Admin Add Member Modal
			$(document).on('input', '#kcm-admin-add-license-number', function() {
				var licenseInput = $(this);
				var expirationInput = $('#kcm-admin-add-license-expiration');
				updateExpirationField(licenseInput, expirationInput);
			});

			// Admin Edit Member Modal
			$(document).on('input', '#kcm-admin-license-number', function() {
				var licenseInput = $(this);
				var expirationInput = $('#kcm-admin-license-expiration');
				updateExpirationField(licenseInput, expirationInput);
			});

				// Function to check and update all license fields
			function checkAllLicenseFields() {
				// Check add form
				var addLicense = $('#kcm-admin-add-license-number');
				var addExpiration = $('#kcm-admin-add-license-expiration');
				if (addLicense.length && addExpiration.length) {
					updateExpirationField(addLicense, addExpiration);
				}

				// Check edit form
				var editLicense = $('#kcm-admin-license-number');
				var editExpiration = $('#kcm-admin-license-expiration');
				if (editLicense.length && editExpiration.length) {
					updateExpirationField(editLicense, editExpiration);
				}
			}

			// Initialize on modal open
			$(document).on('kcm-modal-opened', function() {
				checkAllLicenseFields();
			});

			// Check on page load (initial check)
			setTimeout(checkAllLicenseFields, 100);

			// Check again after a longer delay (for edit modals populated via AJAX)
			setTimeout(checkAllLicenseFields, 500);

			// Listen for changes to the license number field value (including programmatic changes)
			$(document).on('change', '#kcm-admin-license-number, #kcm-admin-add-license-number', function() {
				var licenseInput = $(this);
				var isEditForm = licenseInput.attr('id') === 'kcm-admin-license-number';
				var expirationInput = isEditForm ? $('#kcm-admin-license-expiration') : $('#kcm-admin-add-license-expiration');
				if (expirationInput.length) {
					updateExpirationField(licenseInput, expirationInput);
				}
			});

			// Watch for DOM mutations (when modal content is loaded dynamically)
			var observer = new MutationObserver(function(mutations) {
				mutations.forEach(function(mutation) {
					if (mutation.addedNodes.length) {
						// Check if license fields were added
						setTimeout(checkAllLicenseFields, 50);
					}
				});
			});

			// Observe the body for changes
			if (document.body) {
				observer.observe(document.body, {
					childList: true,
					subtree: true
				});
			}
		},

		/**
		 * Add clear button to license expiration field
		 */
		initLicenseExpirationClearButton: function() {
			// Wait for modals to be loaded
			setTimeout(function() {
				// Add clear button for both add and edit forms
				var editExpirationField = $('#kcm-admin-license-expiration');
				var addExpirationField = $('#kcm-admin-add-license-expiration');

				function addClearButton(field) {
					if (field.length && !field.next('.kcm-clear-date').length) {
						var wrapper = $('<div class="kcm-date-field-wrapper" style="position: relative; display: inline-block; width: 100%;"></div>');
						field.wrap(wrapper);

						var clearBtn = $('<button type="button" class="kcm-clear-date" style="position: absolute; right: 35px; top: 50%; transform: translateY(-50%); background: #dc3545; color: white; border: none; padding: 4px 8px; cursor: pointer; border-radius: 3px; font-size: 12px; z-index: 10;">Clear</button>');

						field.after(clearBtn);

						clearBtn.on('click', function(e) {
							e.preventDefault();
							field.val('').trigger('change');
						});
					}
				}

				addClearButton(editExpirationField);
				addClearButton(addExpirationField);

				// Re-add when modal is opened
				$(document).on('DOMNodeInserted', function() {
					var editField = $('#kcm-admin-license-expiration');
					var addField = $('#kcm-admin-add-license-expiration');
					if (editField.length && !editField.next('.kcm-clear-date').length) {
						addClearButton(editField);
					}
					if (addField.length && !addField.next('.kcm-clear-date').length) {
						addClearButton(addField);
					}
				});
			}, 500);
		},

		/**
		 * Initialize Belt History buttons
		 * NOTE: Belt history functionality is handled by inline JS in class-kcm-admin-menu.php
		 * This function is kept as a stub to prevent errors but doesn't add duplicate handlers
		 */
		initBeltHistoryButtons: function() {
			// Belt history event handlers are defined inline in class-kcm-admin-menu.php
			// to avoid duplicate event binding. This function is intentionally empty.
		},

		// Store current member data for grading
		currentGradingMemberId: null,
		currentGradingMemberName: null,
		gradingExportUrl: null,
		beltColors: [],
		instructors: [],
		gradingRecords: [],

		/**
		 * Show Belt History Modal
		 */
		showBeltHistoryModal: function(memberId, memberName) {
			var self = this;
			self.currentGradingMemberId = memberId;
			self.currentGradingMemberName = memberName;

			// Show modal with loading
			$('#kcm-grading-modal-title').text(i18n('beltGradingHistoryTitle', 'Belt Grading History - ') + memberName);
			$('#kcm-grading-content').html('<div class="kcm-loading">' + i18n('loading', 'Loading...') + '</div>');
			$('#kcm-grading-export-btn, #kcm-add-grading-btn').hide();
			$('#kcm-grading-modal').show();

			// Check if macmGrading is available (premium feature)
			if (typeof macmGrading === 'undefined') {
				$('#kcm-grading-content').html('<div class="kcm-error">' + i18n('premiumFeatureOnly', 'Belt history feature is not available. This is a premium feature.') + '</div>');
				return;
			}

			// Fetch history via AJAX
			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_get_grading_history',
					member_id: memberId,
					nonce: macmGrading.nonce
				},
				success: function(response) {
					if (response.success) {
						self.beltColors = response.data.belt_colors;
						self.instructors = response.data.instructors;
						self.gradingRecords = response.data.records;
						self.gradingExportUrl = response.data.export_url;

						self.renderGradingHistory(response.data.records);
						$('#kcm-grading-export-btn, #kcm-add-grading-btn').show();
					} else {
						$('#kcm-grading-content').html('<div class="kcm-error">' + (response.data.message || i18n('errorLoadingHistory', 'Error loading history. Please try again.')) + '</div>');
					}
				},
				error: function() {
					$('#kcm-grading-content').html('<div class="kcm-error">' + i18n('errorLoadingHistory', 'Error loading history. Please try again.') + '</div>');
				}
			});
		},

		/**
		 * Render grading history table
		 */
		renderGradingHistory: function(records) {
			var self = this;

			if (!records || records.length === 0) {
				$('#kcm-grading-content').html('<p class="kcm-no-records">' + i18n('noGradingHistory', 'No grading history found for this member.') + '</p>');
				return;
			}

			var html = '<table class="wp-list-table widefat fixed striped">';
			html += '<thead><tr>';
			html += '<th>' + i18n('thDate', 'Date') + '</th>';
			html += '<th>' + i18n('thBeltColor', 'Belt Color') + '</th>';
			html += '<th>' + i18n('thExaminer', 'Examiner') + '</th>';
			html += '<th>' + i18n('thScore', 'Score') + '</th>';
			html += '<th>' + i18n('thNotes', 'Notes') + '</th>';
			html += '<th>' + i18n('thActions', 'Actions') + '</th>';
			html += '</tr></thead><tbody>';

			records.forEach(function(record) {
				html += '<tr>';
				html += '<td>' + self.escapeHtml(record.grading_date_formatted) + '</td>';
				html += '<td>' + self.escapeHtml(record.color_name || record.belt_color_key) + '</td>';
				html += '<td>' + self.escapeHtml(record.examiner_display || '-') + '</td>';
				html += '<td>' + self.escapeHtml(record.score || '-') + '</td>';
				html += '<td>' + self.escapeHtml(record.notes || '-') + '</td>';
				html += '<td>';
				html += '<a href="#" class="kcm-edit-grading" data-record-id="' + record.id + '">' + i18n('edit', 'Edit') + '</a> | ';
				html += '<a href="#" class="kcm-delete-grading" data-record-id="' + record.id + '" style="color: #dc3545;">' + i18n('delete', 'Delete') + '</a>';
				html += '</td>';
				html += '</tr>';
			});

			html += '</tbody></table>';
			$('#kcm-grading-content').html(html);
		},

		/**
		 * Show Add Grading Form
		 */
		showAddGradingForm: function() {
			var self = this;

			// Reset form
			$('#kcm-grading-form')[0].reset();
			$('#grading-record-id').val('');
			$('#grading-member-id').val(self.currentGradingMemberId);
			$('#kcm-grading-form-title').text(i18n('addGradingRecord', 'Add Grading Record'));

			// Populate belt colors
			self.populateBeltColorSelect();

			// Populate instructors
			self.populateInstructorSelect();

			$('#kcm-grading-form-modal').show();
		},

		/**
		 * Show Edit Grading Form
		 */
		showEditGradingForm: function(recordId) {
			var self = this;

			// Find record
			var record = self.gradingRecords.find(function(r) {
				return r.id == recordId;
			});

			if (!record) {
				alert(i18n('recordNotFound', 'Record not found'));
				return;
			}

			// Reset form
			$('#kcm-grading-form')[0].reset();
			$('#grading-record-id').val(recordId);
			$('#grading-member-id').val(self.currentGradingMemberId);
			$('#kcm-grading-form-title').text(i18n('editGradingRecord', 'Edit Grading Record'));

			// Populate belt colors
			self.populateBeltColorSelect(record.belt_color_key);

			// Populate instructors
			self.populateInstructorSelect(record.examiner_id);

			// Fill form values
			$('#grading-date').val(record.grading_date);
			$('#grading-examiner-name').val(record.examiner_name || '');
			$('#grading-score').val(record.score || '');
			$('#grading-notes').val(record.notes || '');

			$('#kcm-grading-form-modal').show();
		},

		/**
		 * Populate belt color select
		 */
		populateBeltColorSelect: function(selectedKey) {
			var select = $('#grading-belt-color');
			select.empty().append('<option value="">' + i18n('selectBeltColor', 'Select belt color...') + '</option>');

			this.beltColors.forEach(function(belt) {
				var selected = belt.color_key === selectedKey ? ' selected' : '';
				select.append('<option value="' + belt.color_key + '"' + selected + '>' + belt.color_name + '</option>');
			});
		},

		/**
		 * Populate instructor select
		 */
		populateInstructorSelect: function(selectedId) {
			var select = $('#grading-examiner');
			select.empty().append('<option value="">' + i18n('selectInstructor', 'Select instructor...') + '</option>');

			this.instructors.forEach(function(instructor) {
				var selected = instructor.id == selectedId ? ' selected' : '';
				select.append('<option value="' + instructor.id + '"' + selected + '>' + instructor.full_name + '</option>');
			});
		},

		/**
		 * Save grading record
		 */
		saveGradingRecord: function() {
			var self = this;

			// Validate form
			var beltColor = $('#grading-belt-color').val();
			var gradingDate = $('#grading-date').val();

			if (!beltColor) {
				alert(i18n('pleaseSelectBeltColor', 'Please select a belt color'));
				return;
			}
			if (!gradingDate) {
				alert(i18n('pleaseSelectGradingDate', 'Please select a grading date'));
				return;
			}

			var data = {
				action: 'macm_save_grading',
				nonce: macmGrading.nonce,
				record_id: $('#grading-record-id').val(),
				member_id: $('#grading-member-id').val(),
				belt_color_key: beltColor,
				grading_date: gradingDate,
				examiner_id: $('#grading-examiner').val(),
				examiner_name: $('#grading-examiner-name').val(),
				score: $('#grading-score').val(),
				notes: $('#grading-notes').val()
			};

			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						$('#kcm-grading-form-modal').hide();
						// Reload history
						self.showBeltHistoryModal(self.currentGradingMemberId, self.currentGradingMemberName);
					} else {
						alert(response.data.message || i18n('errorSavingGrading', 'Error saving grading record. Please try again.'));
					}
				},
				error: function() {
					alert(i18n('errorSavingGrading', 'Error saving grading record. Please try again.'));
				}
			});
		},

		/**
		 * Delete grading record
		 */
		deleteGradingRecord: function(recordId) {
			var self = this;

			if (!confirm(i18n('confirmDeleteGrading', 'Are you sure you want to delete this grading record?'))) {
				return;
			}

			$.ajax({
				url: macmGrading.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_delete_grading',
					nonce: macmGrading.nonce,
					record_id: recordId
				},
				success: function(response) {
					if (response.success) {
						// Reload history
						self.showBeltHistoryModal(self.currentGradingMemberId, self.currentGradingMemberName);
					} else {
						alert(response.data.message || i18n('errorDeletingGrading', 'Error deleting grading record. Please try again.'));
					}
				},
				error: function() {
					alert(i18n('errorDeletingGrading', 'Error deleting grading record. Please try again.'));
				}
			});
		},

		/**
		 * Escape HTML for safe display
		 */
		escapeHtml: function(text) {
			if (!text) return '';
			var div = document.createElement('div');
			div.textContent = text;
			return div.innerHTML;
		}
	};

	// Make KCM_Admin available globally
	window.KCM_Admin = KCM_Admin;

})(jQuery);
