(function ($) {
	'use strict';

	if (typeof wppsTemporaryLogin === 'undefined') {
		return;
	}

	var cfg = wppsTemporaryLogin;
	var s = cfg.strings || {};
	var currentLogsLoginId = 0;
	var searchTimer = null;

	function isPremiumUnlocked() {
		return cfg.premiumUnlocked === true || cfg.premiumUnlocked === 1 || cfg.premiumUnlocked === '1';
	}

	function freeExpiryType() {
		return cfg.freeExpiryType || 'day';
	}

	function enforceFreeTierCreateFields() {
		if (isPremiumUnlocked()) {
			return;
		}
		$('#tl-expiry-type').val(freeExpiryType());
		$('#tl-custom-date-row').hide();
		$('#tl-expiry-date').val('');
		$('#tl-single-use').prop('checked', false);
		$('#tl-max-uses').val('0');
		$('#tl-ip-restriction').val('');
		$('#tl-bind-user-agent').prop('checked', false);
	}

	function applyFreeTierSavePayload(formData, isEdit) {
		if (isPremiumUnlocked()) {
			return formData;
		}
		if (!isEdit) {
			formData.expiry_type = freeExpiryType();
			formData.expiry_date = '';
			formData.single_use = '0';
			formData.max_uses = '0';
			formData.ip_restriction = '';
			formData.bind_user_agent = '0';
			return formData;
		}
		if (formData.expiry_type !== freeExpiryType()) {
			delete formData.expiry_type;
			delete formData.expiry_date;
		}
		delete formData.single_use;
		delete formData.max_uses;
		delete formData.ip_restriction;
		delete formData.bind_user_agent;
		return formData;
	}

	function ajaxUrl() {
		return cfg.ajaxUrl || (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
	}

	function tlAjaxData(op, extra) {
		var data = { action: 'tl_admin', tl_op: op, nonce: cfg.nonce };
		if (extra) {
			Object.keys(extra).forEach(function (key) {
				data[key] = extra[key];
			});
		}
		return data;
	}

	function messageFromAjax(xhr, fallback) {
		if (xhr && xhr.responseJSON) {
			if (xhr.responseJSON.data && xhr.responseJSON.data.message) {
				return xhr.responseJSON.data.message;
			}
			if (xhr.responseJSON.message) {
				return xhr.responseJSON.message;
			}
		}
		if (xhr && xhr.responseText) {
			var trimmed = String(xhr.responseText).trim();
			if (trimmed === '0' || trimmed === '-1') {
				return s.handlerMissing || 'Temporary Login is not responding. Reload the page or clear WP PowerSuite cache, then try again.';
			}
			try {
				var parsed = JSON.parse(xhr.responseText);
				if (parsed.data && parsed.data.message) {
					return parsed.data.message;
				}
				if (parsed.message) {
					return parsed.message;
				}
			} catch (e) {
				/* ignore */
			}
		}
		return fallback;
	}

	function hideTopNotice() {
		var $top = $('#tl-notice-top');
		$top.attr('hidden', 'hidden')
			.removeClass('notice notice-success notice-error notice-info');
		$('#tl-notice-top-message').text('');
	}

	function showNotice(message, type, linkUrl) {
		var text = $.trim(String(message || ''));
		if (linkUrl) {
			hideTopNotice();
			var $n = $('#tl-notice');
			$n.removeClass('tl-notice-box--success tl-notice-box--error tl-notice-box--info')
				.addClass('tl-notice-box--' + (type === 'notice-success' ? 'success' : type === 'notice-error' ? 'error' : 'info'));
			$('#tl-notice-message').text(text);
			$('#tl-info-link-input').val(linkUrl);
			$('#tl-notice-link-row').show();
			$n.show();
			return;
		}
		if (text === '') {
			hideTopNotice();
			return;
		}
		$('#tl-notice').hide();
		var $top = $('#tl-notice-top');
		$top.removeClass('notice notice-success notice-error notice-info')
			.addClass('notice ' + (type || 'notice-info'));
		$('#tl-notice-top-message').text(text);
		$top.removeAttr('hidden');
	}

	function resetUserPicker() {
		$('#tl-user-id').val('');
		$('#tl-user-search').val('');
		$('#tl-user-selected').hide().text('');
		$('#tl-user-search-results').attr('hidden', true).empty();
	}

	function setSelectedUser(id, label) {
		$('#tl-user-id').val(id);
		$('#tl-user-search').val('');
		$('#tl-user-selected').text(label).show();
		$('#tl-user-search-results').attr('hidden', true).empty();
	}

	function resetCreateForm() {
		var $form = $('#tl-login-form');
		if ($form.length) {
			$form[0].reset();
		}
		$('#tl-login-id').val('0');
		$('#tl-custom-date-row').hide();
		resetUserPicker();
		$('#tl-form-title-text').text(s.createTitle || 'Create Temporary Login');
		$('#tl-save-login-btn').text(s.createBtn || 'Create Login');
		syncRoleOptions();
		enforceFreeTierCreateFields();
	}

	function syncRoleOptions() {
		var role = $('#tl-role').val();
		var isAdmin = role === 'administrator';
		$('#tl-plugin-theme-row').toggle(isAdmin);
		if (!isAdmin) {
			$('#tl-install-plugins, #tl-delete-plugins, #tl-install-themes, #tl-delete-themes').prop('checked', false);
		}
	}

	function escapeHtml(text) {
		if (text == null) {
			return '';
		}
		return String(text)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function copyText(text, $btn, copiedLabel) {
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(text).then(function () {
				if ($btn && $btn.length) {
					var orig = $btn.html();
					$btn.html(copiedLabel).prop('disabled', true);
					setTimeout(function () {
						$btn.html(orig).prop('disabled', false);
					}, 2000);
				}
			}).catch(function () {
				$('#tl-info-link-input').val(text);
				showNotice(s.copyFallback || 'Copy the link below.', 'notice-info', text);
			});
		} else {
			$('#tl-info-link-input').val(text);
			showNotice(s.copyFallback || 'Copy the link below.', 'notice-info', text);
		}
	}

	function issueCopyLink(loginId, $btn) {
		var cached = $btn.attr('data-login-url') || '';
		if (cached) {
			copyText(cached, $btn, s.copied || 'Copied');
			return;
		}
		if ($btn.hasClass('is-busy')) {
			return;
		}
		$btn.addClass('is-busy').prop('disabled', true);
		$.ajax({
			url: ajaxUrl(),
			type: 'POST',
			dataType: 'json',
			data: tlAjaxData('issue_copy_link', { login_id: loginId }),
			success: function (response) {
				if (response.success && response.data && response.data.login_url) {
					$btn.attr('data-login-url', response.data.login_url);
					copyText(response.data.login_url, $btn, s.copied || 'Copied');
				} else {
					showNotice(
						(response.data && response.data.message) || s.copyLinkFailed || 'Could not copy the login link.',
						'notice-error'
					);
					$btn.prop('disabled', false);
				}
			},
			error: function (xhr) {
				showNotice(
					messageFromAjax(xhr, s.copyLinkFailed || 'Could not copy the login link.'),
					'notice-error'
				);
				$btn.prop('disabled', false);
			},
			complete: function () {
				$btn.removeClass('is-busy');
			}
		});
	}

	function initUserSearch() {
		var $wrap = $('#tl-user-search').parent();
		$wrap.css('position', 'relative');

		$('#tl-user-search').on('input', function () {
			var q = $(this).val().trim();
			clearTimeout(searchTimer);
			if (q.length < 2) {
				$('#tl-user-search-results').attr('hidden', true).empty();
				return;
			}
			searchTimer = setTimeout(function () {
				$('#tl-user-search-results')
					.removeAttr('hidden')
					.empty()
					.append($('<p style="padding:8px 12px;margin:0;"></p>').text(s.searching || 'Searching…'));
				$.ajax({
					url: ajaxUrl(),
					type: 'GET',
					dataType: 'json',
					data: tlAjaxData('search_users', { q: q })
				})
					.done(function (response) {
						var $results = $('#tl-user-search-results').empty();
						if (!response.success || !response.data.users || !response.data.users.length) {
							$results.append(
								'<p style="padding:8px 12px;margin:0;">' + (s.noUsers || 'No users found.') + '</p>'
							);
							return;
						}
						response.data.users.forEach(function (user) {
							$('<button type="button" role="option"></button>')
								.text(user.label)
								.on('click', function () {
									setSelectedUser(user.id, user.label);
								})
								.appendTo($results);
						});
					})
					.fail(function (xhr) {
						$('#tl-user-search-results')
							.empty()
							.append(
								'<p style="padding:8px 12px;margin:0;color:#d63638;">' +
									escapeHtml(messageFromAjax(xhr, s.searchFailed || 'User search failed.')) +
									'</p>'
							);
					});
			}, 250);
		});
	}

	function initTemporaryLogin() {
		$(document)
			.off('click.tl', '#tl-create-login-btn')
			.on('click.tl', '#tl-create-login-btn', function (e) {
				e.preventDefault();
				resetCreateForm();
				$('html, body').animate({ scrollTop: $('#tl-create-edit-form').offset().top - 50 }, 300);
			});

		$(document)
			.off('click.tl', '#tl-form-cancel-btn')
			.on('click.tl', '#tl-form-cancel-btn', function () {
				resetCreateForm();
			});

		$(document)
			.off('click.tl', '.tl-edit-login')
			.on('click.tl', '.tl-edit-login', function () {
				var loginId = $(this).data('login-id');
				$.ajax({
					url: ajaxUrl(),
					type: 'GET',
					dataType: 'json',
					data: tlAjaxData('get_login', { login_id: loginId })
				}).done(function (response) {
					if (!response.success || !response.data.login) {
						return;
					}
					var login = response.data.login;
					$('#tl-login-id').val(login.id);
					if (login.user_id && login.user_email) {
						setSelectedUser(login.user_id, login.user_email);
					}
					$('#tl-user-email').val(login.user_email);
					$('#tl-role').val(login.role);
					$('#tl-expiry-type').val(login.expiry_type);
					if (login.expiry_type === 'custom') {
						$('#tl-custom-date-row').show();
						$('#tl-expiry-date').val(login.expiry_date);
					} else {
						$('#tl-custom-date-row').hide();
					}
					$('#tl-single-use').prop('checked', login.single_use);
					$('#tl-max-uses').val(login.max_uses);
					$('#tl-ip-restriction').val(login.ip_restriction || '');
					$('#tl-bind-user-agent').prop('checked', login.bind_user_agent);
					$('#tl-install-plugins').prop('checked', !!login.install_plugins);
					$('#tl-delete-plugins').prop('checked', !!login.delete_plugins);
					$('#tl-install-themes').prop('checked', !!login.install_themes);
					$('#tl-delete-themes').prop('checked', !!login.delete_themes);
					$('#tl-redirect-to').val(login.redirect_to || '');
					syncRoleOptions();
					$('#tl-form-title-text').text(s.editTitle || 'Edit Temporary Login');
					$('#tl-save-login-btn').text(s.updateBtn || 'Update Login');
					$('html, body').animate({ scrollTop: $('#tl-create-edit-form').offset().top - 50 }, 300);
				});
			});

		$('#tl-role')
			.off('change.tl')
			.on('change.tl', syncRoleOptions);

		$('#tl-expiry-type')
			.off('change.tl')
			.on('change.tl', function () {
				if (!isPremiumUnlocked() && $(this).val() !== freeExpiryType()) {
					$(this).val(freeExpiryType());
					$('#tl-custom-date-row').hide();
					$('#tl-expiry-date').val('');
					return;
				}
				$('#tl-custom-date-row').toggle($(this).val() === 'custom');
			});

		syncRoleOptions();

		$('#tl-save-login-btn')
			.off('click.tl')
			.on('click.tl', function () {
				var $btn = $(this);
				if ($btn.hasClass('is-busy')) {
					return;
				}
				var loginId = $('#tl-login-id').val();
				var isEdit = loginId && loginId !== '0';
				var busyLabel = isEdit ? (s.updating || 'Updating…') : (s.creating || 'Creating…');
				var idleLabel = isEdit ? (s.updateBtn || 'Update Login') : (s.createBtn || 'Create Login');
				var formData = tlAjaxData(isEdit ? 'update_login' : 'create_login', {
					user_id: $('#tl-user-id').val(),
					email: $('#tl-user-email').val(),
					role: $('#tl-role').val(),
					expiry_type: $('#tl-expiry-type').val(),
					expiry_date: $('#tl-expiry-date').val(),
					single_use: $('#tl-single-use').is(':checked') ? '1' : '0',
					max_uses: $('#tl-max-uses').val(),
					ip_restriction: $('#tl-ip-restriction').val(),
					bind_user_agent: $('#tl-bind-user-agent').is(':checked') ? '1' : '0',
					install_plugins: $('#tl-install-plugins').is(':checked') ? '1' : '0',
					delete_plugins: $('#tl-delete-plugins').is(':checked') ? '1' : '0',
					install_themes: $('#tl-install-themes').is(':checked') ? '1' : '0',
					delete_themes: $('#tl-delete-themes').is(':checked') ? '1' : '0',
					redirect_to: $('#tl-redirect-to').val()
				});
				if (isEdit) {
					formData.login_id = loginId;
				}
				formData = applyFreeTierSavePayload(formData, isEdit);
				$btn.prop('disabled', true).addClass('is-busy').empty()
					.append($('<span class="spinner is-active"></span>'))
					.append(document.createTextNode(' ' + String(busyLabel || '')));
				$.ajax({
					url: ajaxUrl(),
					type: 'POST',
					dataType: 'json',
					data: formData
				})
					.done(function (response) {
						var ok = response && (response.success === true || (response.data && response.data.login_url));
						if (ok && response.data) {
							if (!isEdit && response.data.login_url) {
								showNotice(s.createdSuccess || 'Created.', 'notice-success', response.data.login_url);
								$('html, body').animate({ scrollTop: $('#tl-notice').offset().top - 50 }, 300);
							} else {
								location.reload();
							}
						} else {
							showNotice(
								(response.data && response.data.message) || s.genericError || 'An error occurred.',
								'notice-error'
							);
						}
					})
					.fail(function (xhr) {
						showNotice(
							messageFromAjax(xhr, s.requestFailed || 'Request failed.'),
							'notice-error'
						);
					})
					.always(function () {
						$btn.prop('disabled', false).removeClass('is-busy').text(idleLabel);
					});
			});

		$(document)
			.off('click.tl', '.tl-copy-link')
			.on('click.tl', '.tl-copy-link', function () {
				var $btn = $(this);
				var loginId = $btn.data('login-id');
				if (!loginId) {
					return;
				}
				issueCopyLink(loginId, $btn);
			});

		$(document)
			.off('click.tl', '.tl-rotate-link')
			.on('click.tl', '.tl-rotate-link', function () {
				var $btn = $(this);
				var loginId = $btn.data('login-id');
				if (!loginId || $btn.hasClass('is-busy')) {
					return;
				}
				if (!window.confirm(s.confirmRotateLink || 'Generate a new link? The previous URL will stop working.')) {
					return;
				}
				$btn.addClass('is-busy').prop('disabled', true);
				$.ajax({
					url: ajaxUrl(),
					type: 'POST',
					dataType: 'json',
					data: tlAjaxData('regenerate_login_link', { login_id: loginId }),
					success: function (response) {
						if (response.success && response.data && response.data.login_url) {
							$('.tl-copy-link[data-login-id="' + loginId + '"]').attr('data-login-url', response.data.login_url);
							copyText(response.data.login_url, $btn, s.copied || 'Copied');
							showNotice(s.rotatedCopied || 'New link copied. The previous URL no longer works.', 'notice-success', response.data.login_url);
						} else {
							showNotice(
								(response.data && response.data.message) || s.rotateLinkFailed || 'Could not rotate the login link.',
								'notice-error'
							);
							$btn.prop('disabled', false);
						}
					},
					error: function (xhr) {
						showNotice(
							messageFromAjax(xhr, s.rotateLinkFailed || 'Could not rotate the login link.'),
							'notice-error'
						);
						$btn.prop('disabled', false);
					},
					complete: function () {
						$btn.removeClass('is-busy');
					}
				});
			});

		$(document)
			.off('click.tl', '#tl-info-copy-btn')
			.on('click.tl', '#tl-info-copy-btn', function () {
				var text = $('#tl-info-link-input').val();
				if (text) {
					copyText(text, $(this), s.copiedExclaim || 'Copied!');
				}
			});

		$(document)
			.off('click.tl', '.tl-revoke-login')
			.on('click.tl', '.tl-revoke-login', function () {
				var loginId = $(this).data('login-id');
				if (!window.confirm(s.confirmRevoke || 'Revoke this login?')) {
					return;
				}
				$.post(ajaxUrl(), tlAjaxData('revoke_login', { login_id: loginId })).done(function (response) {
					if (response.success) {
						location.reload();
					} else {
						showNotice((response.data && response.data.message) || s.revokeFailed || 'Failed.', 'notice-error');
					}
				});
			});

		$(document)
			.off('click.tl', '.tl-enable-login')
			.on('click.tl', '.tl-enable-login', function () {
				var loginId = $(this).data('login-id');
				if (!window.confirm(s.confirmEnable || 'Re-enable this login?')) {
					return;
				}
				$.post(ajaxUrl(), tlAjaxData('enable_login', { login_id: loginId })).done(function (response) {
					if (response.success) {
						location.reload();
					} else {
						showNotice((response.data && response.data.message) || s.enableFailed || 'Failed.', 'notice-error');
					}
				});
			});

		$(document)
			.off('click.tl', '.tl-delete-login')
			.on('click.tl', '.tl-delete-login', function () {
				var loginId = $(this).data('login-id');
				if (!window.confirm(s.confirmDelete || 'Delete permanently?')) {
					return;
				}
				$.post(ajaxUrl(), tlAjaxData('delete_login', { login_id: loginId })).done(function (response) {
					if (response.success) {
						location.reload();
					} else {
						showNotice((response.data && response.data.message) || s.deleteFailed || 'Failed.', 'notice-error');
					}
				});
			});

		$(document)
			.off('click.tl', '.tl-view-logs')
			.on('click.tl', '.tl-view-logs', function () {
				currentLogsLoginId = $(this).data('login-id');
				$('#tl-logs-modal').show().attr('aria-hidden', 'false');
				$('body').addClass('tl-logs-modal-open');
				$('#tl-logs-content').empty().append(
					$('<p style="text-align:center;padding:20px;"></p>')
						.append($('<span class="spinner is-active"></span>'))
						.append(document.createTextNode(' ' + String(s.loadingLogs || 'Loading…')))
				);
				$.get(ajaxUrl(), tlAjaxData('get_logs', { login_id: currentLogsLoginId })).done(function (response) {
					if (!response.success || !response.data.logs) {
						$('#tl-logs-content').empty().append(
							$('<p style="text-align:center;padding:20px;color:#d63638;"></p>').text(
								s.logsLoadFailed || 'Failed to load logs.'
							)
						);
						return;
					}
					var logs = response.data.logs.filter(function (log) {
						return log.action !== 'login_created' && log.action !== 'page_access';
					});
					if (!logs.length) {
						$('#tl-logs-content').empty().append(
							$('<p style="text-align:center;padding:20px;"></p>').text(s.logsUnused || 'Not used yet.')
						);
						return;
					}
					var html =
						'<table class="wp-list-table widefat fixed striped"><thead><tr>' +
						'<th>' +
						(s.colTime || 'Time') +
						'</th><th>' +
						(s.colAction || 'Action') +
						'</th><th>' +
						(s.colIp || 'IP') +
						'</th><th>' +
						(s.colUa || 'User Agent') +
						'</th><th>' +
						(s.colPage || 'Page') +
						'</th></tr></thead><tbody>';
					logs.forEach(function (log) {
						var time = log.logged_at ? escapeHtml(new Date(log.logged_at).toLocaleString()) : '-';
						var action = log.action
							? escapeHtml(
									log.action.replace(/_/g, ' ').replace(/\b\w/g, function (l) {
										return l.toUpperCase();
									})
								)
							: '-';
						var ip = escapeHtml(log.ip_address || '-');
						var ua = escapeHtml(log.user_agent ? log.user_agent.substring(0, 80) + '…' : '-');
						var page = escapeHtml(log.page_accessed || '-');
						html +=
							'<tr><td>' +
							time +
							'</td><td>' +
							action +
							'</td><td>' +
							ip +
							'</td><td><small>' +
							ua +
							'</small></td><td><small>' +
							page +
							'</small></td></tr>';
					});
					html += '</tbody></table>';
					$('#tl-logs-content').html(html);
				}).fail(function () {
					$('#tl-logs-content').empty().append(
						$('<p style="text-align:center;padding:20px;color:#d63638;"></p>').text(s.logsError || 'Error.')
					);
				});
			});

		function closeLogsModal() {
			$('#tl-logs-modal').hide().attr('aria-hidden', 'true');
			$('body').removeClass('tl-logs-modal-open');
		}

		$(document).off('click.tl', '#tl-logs-close-btn').on('click.tl', '#tl-logs-close-btn', closeLogsModal);
		$(document)
			.off('click.tl', '#tl-logs-modal .tl-modal__overlay')
			.on('click.tl', '#tl-logs-modal .tl-modal__overlay', closeLogsModal);
		$(document)
			.off('keydown.tl-logs')
			.on('keydown.tl-logs', function (e) {
				if (e.key === 'Escape' && $('#tl-logs-modal').is(':visible')) {
					closeLogsModal();
				}
			});

		$(document)
			.off('click.tl', '#tl-export-logs-btn')
			.on('click.tl', '#tl-export-logs-btn', function () {
				if (currentLogsLoginId) {
					window.location.href =
						ajaxUrl() +
						'?action=tl_admin&tl_op=export_logs&login_id=' +
						currentLogsLoginId +
						'&nonce=' +
						encodeURIComponent(cfg.nonce);
				}
			});

		initUserSearch();
	}

	$(function () {
		initTemporaryLogin();
	});

	document.addEventListener('wp-powersuite-modal-loaded', function () {
		setTimeout(initTemporaryLogin, 100);
	});
})(jQuery);
