/**
 * Admin Settings Page JavaScript
 *
 * @package Karate_Club_Manager
 * @since 1.0.0
 */

(function($) {
	'use strict';

	/**
	 * Return a translated string from the localized macmSettings object.
	 *
	 * @param {string} key      Key in macmSettings.i18n.
	 * @param {string} fallback Fallback string when the key is unavailable.
	 * @return {string}
	 */
	function i18n(key, fallback) {
		return (typeof macmSettings !== 'undefined' && macmSettings.i18n && macmSettings.i18n[key]) ? macmSettings.i18n[key] : fallback;
	}

	/**
	 * Initialize settings page functionality
	 */
	function initSettings() {
		// Select All / Deselect All is already handled inline in the template
		// Additional JavaScript functionality can be added here as needed

		// Show a confirmation message when changing protection settings
		$('.kcm-page-checkbox').on('change', function() {
			var checkbox = $(this);
			var pageName = checkbox.parent().find('strong').text();

			// Optional: Add visual feedback
			if (checkbox.is(':checked')) {
				checkbox.parent().addClass('page-protected');
			} else {
				checkbox.parent().removeClass('page-protected');
			}
		});
	}

	/**
	 * Button Colours Settings - Color Picker Sync
	 */
	function initButtonColoursPicker() {
		// Check if button colours elements exist
		if ($('#kcm_button_gradient_start').length === 0) {
			return;
		}

		// Sync color picker with text input
		$('#kcm_button_gradient_start').on('input', function() {
			$('#kcm_button_gradient_start_text').val($(this).val());
			updateButtonPreview();
		});

		$('#kcm_button_gradient_start_text').on('input', function() {
			var color = $(this).val();
			if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
				$('#kcm_button_gradient_start').val(color);
				updateButtonPreview();
			}
		});

		$('#kcm_button_gradient_end').on('input', function() {
			$('#kcm_button_gradient_end_text').val($(this).val());
			updateButtonPreview();
		});

		$('#kcm_button_gradient_end_text').on('input', function() {
			var color = $(this).val();
			if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
				$('#kcm_button_gradient_end').val(color);
				updateButtonPreview();
			}
		});

		// Reset to default
		$('#kcm-reset-button-gradient').on('click', function() {
			$('#kcm_button_gradient_start').val('#B11226');
			$('#kcm_button_gradient_start_text').val('#B11226');
			$('#kcm_button_gradient_end').val('#8F0E1E');
			$('#kcm_button_gradient_end_text').val('#8F0E1E');
			updateButtonPreview();
		});
	}

	/**
	 * Update button preview
	 */
	function updateButtonPreview() {
		var startColor = $('#kcm_button_gradient_start').val();
		var endColor = $('#kcm_button_gradient_end').val();
		var gradient = 'linear-gradient(135deg, ' + startColor + ' 0%, ' + endColor + ' 100%)';
		$('#kcm-button-preview').css('background', gradient);
	}

	/**
	 * Email Design Settings - Color Picker Sync
	 */
	function initEmailDesignPicker() {
		// Check if email design elements exist
		if ($('#kcm_email_gradient_start').length === 0) {
			return;
		}

		// Sync color picker with text input
		$('#kcm_email_gradient_start').on('input', function() {
			$('#kcm_email_gradient_start_text').val($(this).val());
			updateEmailPreview();
		});

		$('#kcm_email_gradient_start_text').on('input', function() {
			var color = $(this).val();
			if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
				$('#kcm_email_gradient_start').val(color);
				updateEmailPreview();
			}
		});

		$('#kcm_email_gradient_end').on('input', function() {
			$('#kcm_email_gradient_end_text').val($(this).val());
			updateEmailPreview();
		});

		$('#kcm_email_gradient_end_text').on('input', function() {
			var color = $(this).val();
			if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
				$('#kcm_email_gradient_end').val(color);
				updateEmailPreview();
			}
		});

		// Reset to default
		$('#kcm-reset-gradient').on('click', function() {
			$('#kcm_email_gradient_start').val('#B11226');
			$('#kcm_email_gradient_start_text').val('#B11226');
			$('#kcm_email_gradient_end').val('#8F0E1E');
			$('#kcm_email_gradient_end_text').val('#8F0E1E');
			updateEmailPreview();
		});
	}

	/**
	 * Update email preview
	 */
	function updateEmailPreview() {
		var startColor = $('#kcm_email_gradient_start').val();
		var endColor = $('#kcm_email_gradient_end').val();
		var gradient = 'linear-gradient(135deg, ' + startColor + ' 0%, ' + endColor + ' 100%)';
		$('#kcm-gradient-preview-header').css('background', gradient);
	}

	/**
	 * User Accounts - Bulk Create WP Users
	 */
	function initBulkUserAccounts() {
		// Check if bulk user table exists.
		if ($('#macm-bulk-user-table').length === 0) {
			return;
		}

		var $selectAll = $('#macm-bulk-user-select-all');
		var $checkboxes = $('.macm-bulk-user-checkbox');
		var $createBtn = $('#macm-bulk-create-users-btn');

		// Update button state based on checked checkboxes.
		function updateButtonState() {
			$createBtn.prop('disabled', $checkboxes.filter(':checked').length === 0);
		}

		// Select All toggle.
		$selectAll.on('change', function() {
			$checkboxes.prop('checked', $(this).is(':checked'));
			updateButtonState();
		});

		// Individual checkbox.
		$checkboxes.on('change', function() {
			$selectAll.prop('checked', $checkboxes.length === $checkboxes.filter(':checked').length);
			updateButtonState();
		});

		// Create button click.
		$createBtn.on('click', function() {
			var members = [];
			var missingEmails = [];

			$checkboxes.filter(':checked').each(function() {
				var memberId = $(this).data('member-id');
				var email = $('.macm-bulk-user-email[data-member-id="' + memberId + '"]').val();

				if (!email || !email.trim()) {
					var memberName = $(this).closest('tr').find('td:eq(0)').text().trim();
					missingEmails.push(memberName);
				}

				members.push({
					id: memberId,
					email: (email || '').trim()
				});
			});

			if (missingEmails.length > 0) {
				alert(i18n('enterEmailFor', 'Please enter an email address for: %s').replace('%s', missingEmails.join(', ')));
				return;
			}

			if (!confirm(i18n('confirmCreateAccounts', 'Create WordPress user accounts for %d member(s)? Login credentials will be emailed to each member.').replace('%d', members.length))) {
				return;
			}

			$createBtn.prop('disabled', true);
			$('#macm-bulk-user-spinner').addClass('is-active');
			$('#macm-bulk-user-messages').empty();

			$.ajax({
				url: macmAdmin.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_bulk_create_wp_users',
					nonce: macmAdmin.nonce,
					members: members
				},
				success: function(response) {
					$('#macm-bulk-user-spinner').removeClass('is-active');

					if (response.success) {
						var html = '';

						if (response.data.created.length > 0) {
							html += '<div class="notice notice-success"><p>';
							html += i18n('createdAccountsFor', 'Successfully created accounts for: ') + response.data.created.join(', ');
							html += '</p></div>';
						}

						if (response.data.linked && response.data.linked.length > 0) {
							html += '<div class="notice notice-info"><p>';
							html += i18n('linkedToExisting', 'Linked to existing accounts: ') + response.data.linked.join(', ');
							html += '</p></div>';
						}

						if (response.data.errors.length > 0) {
							html += '<div class="notice notice-error"><p>';
							html += response.data.errors.join('<br>');
							html += '</p></div>';
						}

						$('#macm-bulk-user-messages').html(html);

						if (response.data.created.length > 0 || (response.data.linked && response.data.linked.length > 0)) {
							$('#macm-bulk-user-messages').append(
								'<p style="margin-top: 10px;"><button type="button" class="button" onclick="location.reload();">' + i18n('refreshPage', 'Refresh Page') + '</button></p>'
							);
						} else {
							$createBtn.prop('disabled', false);
						}
					} else {
						$('#macm-bulk-user-messages').html(
							'<div class="notice notice-error"><p>' + (response.data.message || i18n('errorOccurred', 'An error occurred.')) + '</p></div>'
						);
						$createBtn.prop('disabled', false);
					}
				},
				error: function() {
					$('#macm-bulk-user-spinner').removeClass('is-active');
					$('#macm-bulk-user-messages').html(
						'<div class="notice notice-error"><p>' + i18n('ajaxError', 'AJAX error occurred. Please try again.') + '</p></div>'
					);
					$createBtn.prop('disabled', false);
				}
			});
		});
	}

	/**
	 * Document ready
	 */
	$(document).ready(function() {
		initSettings();
		initButtonColoursPicker();
		initEmailDesignPicker();
		initBulkUserAccounts();
	});

})(jQuery);
