(function () {
	'use strict';

	var cfg = window.LogisticaPanelAuth || {};

	function query(selector, root) {
		return (root || document).querySelector(selector);
	}

	function post(action, data) {
		var body = new FormData();
		body.append('action', action);
		body.append('nonce', cfg.authNonce || '');

		Object.keys(data || {}).forEach(function (key) {
			body.append(key, data[key]);
		});

		return fetch(cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			body: body
		}).then(function (response) {
			return response.json();
		});
	}

	function showNotice(node, message, isError) {
		if (!node) {
			return;
		}

		node.hidden = !message;
		node.textContent = message || '';
		node.classList.toggle('logistica-panel-auth__notice--error', !!isError);
	}

	function initLogin(root) {
		var form = query('[data-logistica-panel-auth-form]', root);
		var notice = query('[data-logistica-panel-auth-notice]', root);
		var submitBtn = form ? form.querySelector('[type="submit"]') : null;
		var loginView = query('[data-logistica-panel-view="login"]', root);
		var forgotView = query('[data-logistica-panel-view="forgot"]', root);
		var showForgot = query('[data-logistica-panel-show-forgot]', root);
		var showLogin = query('[data-logistica-panel-show-login]', root);

		if (showForgot && loginView && forgotView) {
			showForgot.addEventListener('click', function () {
				loginView.hidden = true;
				forgotView.hidden = false;
				showNotice(notice, '', false);
			});
		}

		if (showLogin && loginView && forgotView) {
			showLogin.addEventListener('click', function () {
				forgotView.hidden = true;
				loginView.hidden = false;
			});
		}

		if (form) {
			form.addEventListener('submit', function (event) {
				event.preventDefault();

				if (submitBtn) {
					submitBtn.disabled = true;
				}

				showNotice(notice, '', false);

				var formData = new FormData(form);

				post('logistica_panel_login', {
					username: formData.get('username') || '',
					password: formData.get('password') || '',
					remember: formData.get('remember') ? '1' : ''
				})
					.then(function (result) {
						if (result && result.success) {
							if (result.data && result.data.redirect) {
								window.location.href = result.data.redirect;
								return;
							}
							window.location.reload();
							return;
						}

						var message = (result && result.data && result.data.message) || 'No se pudo iniciar sesión.';
						showNotice(notice, message, true);
					})
					.catch(function () {
						showNotice(notice, 'Error de conexión. Inténtalo de nuevo.', true);
					})
					.finally(function () {
						if (submitBtn) {
							submitBtn.disabled = false;
						}
					});
			});
		}

		initForgot(root);
	}

	function initForgot(root) {
		var form = query('[data-logistica-panel-forgot-form]', root);
		if (!form) {
			return;
		}

		var notice = query('[data-logistica-panel-forgot-notice]', root);
		var success = query('[data-logistica-panel-forgot-success]', root);
		var submitBtn = form.querySelector('[type="submit"]');

		form.addEventListener('submit', function (event) {
			event.preventDefault();

			if (submitBtn) {
				submitBtn.disabled = true;
			}

			showNotice(notice, '', false);
			if (success) {
				success.hidden = true;
				success.textContent = '';
			}

			var formData = new FormData(form);

			post('logistica_panel_forgot_password', {
				identity: formData.get('identity') || ''
			})
				.then(function (result) {
					if (!result || !result.success) {
						var message = (result && result.data && result.data.message) || 'No se pudo procesar la solicitud.';
						showNotice(notice, message, true);
						return;
					}

					var data = result.data || {};
					if (success) {
						success.hidden = false;
						if (data.resetUrl) {
							success.innerHTML = (data.message || '') + ' <a href="' + data.resetUrl + '">Restablecer contraseña ahora</a>';
						} else {
							success.textContent = data.message || 'Revisa tu correo para continuar.';
						}
					} else {
						showNotice(notice, data.message || 'Revisa tu correo para continuar.', false);
					}
					form.reset();
				})
				.catch(function () {
					showNotice(notice, 'Error de conexión. Inténtalo de nuevo.', true);
				})
				.finally(function () {
					if (submitBtn) {
						submitBtn.disabled = false;
					}
				});
		});
	}

	function initReset(root) {
		var form = query('[data-logistica-panel-reset-form]', root);
		if (!form) {
			return;
		}

		var notice = query('[data-logistica-panel-auth-notice]', root);
		var submitBtn = form.querySelector('[type="submit"]');

		form.addEventListener('submit', function (event) {
			event.preventDefault();

			if (submitBtn) {
				submitBtn.disabled = true;
			}

			showNotice(notice, '', false);

			var formData = new FormData(form);

			post('logistica_panel_reset_password', {
				key: formData.get('key') || '',
				login: formData.get('login') || '',
				password: formData.get('password') || '',
				password_confirm: formData.get('password_confirm') || ''
			})
				.then(function (result) {
					if (result && result.success) {
						var data = result.data || {};
						showNotice(notice, data.message || 'Contraseña actualizada.', false);
						if (data.redirect) {
							window.setTimeout(function () {
								window.location.href = data.redirect;
							}, 1200);
						}
						return;
					}

					var message = (result && result.data && result.data.message) || 'No se pudo actualizar la contraseña.';
					showNotice(notice, message, true);
				})
				.catch(function () {
					showNotice(notice, 'Error de conexión. Inténtalo de nuevo.', true);
				})
				.finally(function () {
					if (submitBtn) {
						submitBtn.disabled = false;
					}
				});
		});
	}

	function initLogout() {
		document.addEventListener('click', function (event) {
			var button = event.target.closest('[data-logistica-panel-logout]');
			if (!button) {
				return;
			}

			event.preventDefault();
			button.disabled = true;

			post('logistica_panel_logout', {})
				.then(function (result) {
					if (result && result.success) {
						window.location.reload();
						return;
					}

					button.disabled = false;
				})
				.catch(function () {
					button.disabled = false;
				});
		});
	}

	function init() {
		var loginRoot = document.querySelector('[data-logistica-panel-login]');
		if (loginRoot) {
			initLogin(loginRoot);
		}

		var resetRoot = document.querySelector('[data-logistica-panel-reset]');
		if (resetRoot) {
			initReset(resetRoot);
		}

		initLogout();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
