(function () {
	'use strict';

	function initPasswordToggles(root) {
		root.querySelectorAll('[data-logistica-password-toggle]').forEach(function (btn) {
			btn.addEventListener('click', function () {
				var wrap = btn.closest('.logistica-user-form__password-wrap');
				if (!wrap) {
					return;
				}
				var input = wrap.querySelector('[data-logistica-password]');
				var icon = btn.querySelector('.dashicons');
				if (!input || !icon) {
					return;
				}
				var show = input.type === 'password';
				input.type = show ? 'text' : 'password';
				icon.classList.toggle('dashicons-visibility', !show);
				icon.classList.toggle('dashicons-hidden', show);
				btn.setAttribute(
					'aria-label',
					show ? 'Ocultar contraseña' : 'Mostrar contraseña'
				);
			});
		});
	}

	function initRolePicker(root) {
		var picker = root.querySelector('[data-logistica-role-picker]');
		if (!picker) {
			return;
		}

		picker.addEventListener('change', function (event) {
			var input = event.target;
			if (!input || input.name !== 'logistica_jb_role') {
				return;
			}
			picker.querySelectorAll('.logistica-user-form__role-card').forEach(function (card) {
				card.classList.remove('is-selected');
			});
			var card = input.closest('.logistica-user-form__role-card');
			if (card) {
				card.classList.add('is-selected');
			}
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('[data-logistica-user-form]').forEach(function (form) {
			initPasswordToggles(form);
			initRolePicker(form);
		});
	});
})();
