(function ($) {
	'use strict';

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

	var cfg = wppsLoginSessionManager;
	var selectedUsers = {};
	var currentPage = 1;
	var currentSearch = '';
	var searchTimer = null;

	function post(action, data) {
		return $.ajax({
			url: cfg.ajaxUrl,
			type: 'POST',
			dataType: 'json',
			data: $.extend(
				{
					action: action,
					nonce: cfg.nonce
				},
				data || {}
			)
		});
	}

	function escapeHtml(text) {
		return $('<div/>').text(text || '').html();
	}

	function badgeHtml(badges) {
		var html = '';
		if (!badges || !badges.length) {
			return html;
		}
		if (badges.indexOf('current') !== -1) {
			html += '<span class="wpps-lsm-badge wpps-lsm-badge-current">' + escapeHtml(cfg.strings.currentSession) + '</span>';
		}
		if (badges.indexOf('login_as') !== -1) {
			html += '<span class="wpps-lsm-badge wpps-lsm-badge-login-as">' + escapeHtml(cfg.strings.loginAsBadge) + '</span>';
		}
		if (badges.indexOf('temporary_login') !== -1) {
			html += '<span class="wpps-lsm-badge wpps-lsm-badge-temp">' + escapeHtml(cfg.strings.tempLoginBadge) + '</span>';
		}
		return html;
	}

	function updateStats(stats) {
		if (!stats) {
			return;
		}
		$('[data-stat="total_sessions"]').text(stats.total_sessions || 0);
		$('[data-stat="users_logged_in"]').text(stats.users_logged_in || 0);

		var $roles = $('[data-stat="sessions_by_role"]');
		$roles.empty();
		var roleStats = stats.sessions_by_role || {};
		var keys = Object.keys(roleStats);
		if (!keys.length) {
			$roles.append('<span class="wpps-lsm-muted">' + escapeHtml(cfg.strings.noSessions) + '</span>');
			return;
		}
		keys.forEach(function (role) {
			$roles.append('<span class="wpps-lsm-role-pill">' + escapeHtml(role + ': ' + roleStats[role]) + '</span>');
		});
	}

	function updatePagination(pagination) {
		var $wrap = $('#wpps-lsm-pagination');
		if (!$wrap.length || !pagination) {
			return;
		}

		var totalPages = pagination.total_pages || 0;
		if (totalPages <= 1) {
			$wrap.prop('hidden', true);
			return;
		}

		$wrap.prop('hidden', false);
		$('#wpps-lsm-prev-page').prop('disabled', currentPage <= 1);
		$('#wpps-lsm-next-page').prop('disabled', currentPage >= totalPages);
		$('#wpps-lsm-page-info').text(
			(cfg.strings.page || 'Page') + ' ' + currentPage + ' ' + (cfg.strings.of || 'of') + ' ' + totalPages
		);
	}

	function renderTable(sessions) {
		var $body = $('#wpps-lsm-table-body');
		if (!$body.length) {
			return;
		}

		selectedUsers = {};
		$('#wpps-lsm-bulk-logout').prop('disabled', true);
		$('#wpps-lsm-select-all').prop('checked', false);

		if (!sessions || !sessions.length) {
			$body.html('<tr><td colspan="8">' + escapeHtml(cfg.strings.noSessions) + '</td></tr>');
			return;
		}

		var rows = sessions.map(function (session) {
			var user = session.user || {};
			var userId = session.user_id || user.id || 0;
			var userLabel = user.display_name || user.login || ('#' + userId);
			var userHtml = user.edit_url
				? '<a class="wpps-lsm-user-link" href="' + escapeHtml(user.edit_url) + '">' + escapeHtml(userLabel) + '</a>'
				: escapeHtml(userLabel);

			return [
				'<tr data-user-id="', userId, '" data-verifier="', session.verifier || '', '">',
				'<th scope="row" class="check-column">',
				'<input type="checkbox" class="wpps-lsm-user-select" value="', userId, '" aria-label="', escapeHtml(userLabel), '" />',
				'</th>',
				'<td>', userHtml, badgeHtml(session.badges), '</td>',
				'<td>', escapeHtml(user.role_label || user.primary_role || ''), '</td>',
				'<td>', escapeHtml(session.ip || ''), '</td>',
				'<td>', escapeHtml(session.device || ''), '</td>',
				'<td>', escapeHtml(session.login_formatted || ''), '</td>',
				'<td>', escapeHtml(session.expiration_formatted || ''), '</td>',
				'<td><button type="button" class="button button-secondary wpps-lsm-destroy-session" data-user-id="', userId, '" data-verifier="', session.verifier || '', '">', escapeHtml(cfg.strings.logOutSession), '</button></td>',
				'</tr>'
			].join('');
		});

		$body.html(rows.join(''));
	}

	function handleDestroyResponse(response) {
		if (response && response.success && response.data && response.data.destroyed_current && response.data.redirect) {
			window.location.href = response.data.redirect;
			return;
		}
		if ($('#wpps-lsm-table-body').length) {
			loadSessions(currentPage);
		} else {
			window.location.reload();
		}
	}

	function openSessionsAccordion() {
		var accordion = document.getElementById('wpps-lsm-acc-sessions');
		if (!accordion) {
			return;
		}

		accordion.classList.add('is-open');
		var header = accordion.querySelector('.wpps-ts-accordion-header');
		if (header) {
			header.setAttribute('aria-expanded', 'true');
		}

		var target = document.getElementById('wpps-lsm-modal-sessions');
		if (target) {
			window.requestAnimationFrame(function () {
				target.scrollIntoView({ behavior: 'smooth', block: 'start' });
			});
		}
	}

	function maybeOpenSessionsSection() {
		var section = sessionStorage.getItem('wpps_reopen_modal_section');
		if (section !== 'sessions') {
			return;
		}

		sessionStorage.removeItem('wpps_reopen_modal_section');
		openSessionsAccordion();
	}

	function initSessionsPanel() {
		if (!$('#wpps-lsm-table-body').length) {
			return;
		}
		maybeOpenSessionsSection();
		currentPage = 1;
		loadSessions(1);
	}

	function loadSessions(page) {
		currentPage = page || 1;

		var $loading = $('#wpps-lsm-loading');
		if ($loading.length) {
			$loading.prop('hidden', false);
		}

		var payload = {
			page: currentPage,
			per_page: cfg.perPage || 50,
			search: currentSearch
		};

		if (cfg.filterUserId) {
			payload.filter_user_id = cfg.filterUserId;
		}

		return post('wpps_login_session_manager_list', payload)
			.done(function (response) {
				if (!response || !response.success) {
					window.alert((response && response.data && response.data.message) || cfg.strings.error);
					return;
				}
				updateStats(response.data.stats);
				renderTable(response.data.sessions);
				updatePagination(response.data.pagination);
			})
			.fail(function () {
				window.alert(cfg.strings.error);
			})
			.always(function () {
				if ($loading.length) {
					$loading.prop('hidden', true);
				}
			});
	}

	function readButtonData($btn) {
		var el = $btn[0];
		if (!el) {
			return { userId: 0, verifier: '' };
		}
		var rowEl = $btn.closest('tr')[0];
		return {
			userId: parseInt(el.getAttribute('data-user-id') || (rowEl && rowEl.getAttribute('data-user-id')) || '0', 10) || 0,
			verifier: el.getAttribute('data-verifier') || (rowEl && rowEl.getAttribute('data-verifier')) || ''
		};
	}

	function destroySession(userId, verifier) {
		if (!window.confirm(cfg.strings.confirmDestroy)) {
			return;
		}

		post('wpps_login_session_manager_destroy', {
			user_id: userId,
			verifier: verifier
		})
			.done(function (response) {
				if (!response || !response.success) {
					window.alert((response && response.data && response.data.message) || cfg.strings.error);
					return;
				}
				handleDestroyResponse(response);
			})
			.fail(function () {
				window.alert(cfg.strings.error);
			});
	}

	function destroyAllUser(userId) {
		if (!window.confirm(cfg.strings.confirmDestroyAll)) {
			return;
		}

		post('wpps_login_session_manager_destroy_all_user', {
			user_id: userId
		})
			.done(function (response) {
				if (!response || !response.success) {
					window.alert((response && response.data && response.data.message) || cfg.strings.error);
					return;
				}
				handleDestroyResponse(response);
			})
			.fail(function () {
				window.alert(cfg.strings.error);
			});
	}

	function destroyBulkUsers() {
		var userIds = Object.keys(selectedUsers).filter(function (id) {
			return selectedUsers[id];
		});

		if (!userIds.length) {
			return;
		}

		if (!window.confirm(cfg.strings.confirmBulk)) {
			return;
		}

		post('wpps_login_session_manager_destroy_all_user', {
			user_ids: userIds
		})
			.done(function (response) {
				if (!response || !response.success) {
					window.alert((response && response.data && response.data.message) || cfg.strings.error);
					return;
				}
				handleDestroyResponse(response);
			})
			.fail(function () {
				window.alert(cfg.strings.error);
			});
	}

	function destroyAllSite() {
		if (!cfg.canDestroySite) {
			return;
		}
		if (!window.confirm(cfg.strings.confirmDestroySite)) {
			return;
		}

		post('wpps_login_session_manager_destroy_all_site', {})
			.done(function (response) {
				if (!response || !response.success) {
					window.alert((response && response.data && response.data.message) || cfg.strings.error);
					return;
				}
				if (response.data && response.data.redirect) {
					window.location.href = response.data.redirect;
				}
			})
			.fail(function () {
				window.alert(cfg.strings.error);
			});
	}

	function updateBulkState() {
		var count = Object.keys(selectedUsers).filter(function (id) {
			return selectedUsers[id];
		}).length;
		$('#wpps-lsm-bulk-logout').prop('disabled', count < 1);
	}

	$(document).on('click', '.wpps-lsm-destroy-session', function (event) {
		event.preventDefault();
		event.stopPropagation();
		var data = readButtonData($(this));
		if (!data.userId || !data.verifier) {
			window.alert(cfg.strings.error);
			return;
		}
		destroySession(data.userId, data.verifier);
	});

	$(document).on('click', '.wpps-lsm-destroy-all-user', function (event) {
		event.preventDefault();
		var data = readButtonData($(this));
		destroyAllUser(data.userId);
	});

	$(document).on('change', '.wpps-lsm-user-select', function () {
		var userId = String($(this).val());
		selectedUsers[userId] = $(this).is(':checked');
		updateBulkState();
	});

	$(document).on('change', '#wpps-lsm-select-all', function () {
		var checked = $(this).is(':checked');
		$('.wpps-lsm-user-select').each(function () {
			$(this).prop('checked', checked).trigger('change');
		});
	});

	$(function () {
		$(document).on('click', '#wpps-lsm-refresh', function () {
			loadSessions(currentPage);
		});
		$(document).on('click', '#wpps-lsm-bulk-logout', destroyBulkUsers);
		$(document).on('click', '#wpps-lsm-destroy-site', destroyAllSite);
		$(document).on('click', '#wpps-lsm-prev-page', function () {
			if (currentPage > 1) {
				loadSessions(currentPage - 1);
			}
		});
		$(document).on('click', '#wpps-lsm-next-page', function () {
			loadSessions(currentPage + 1);
		});
		$(document).on('input', '#wpps-lsm-search', function () {
			var value = String($(this).val() || '');
			window.clearTimeout(searchTimer);
			searchTimer = window.setTimeout(function () {
				currentSearch = value.trim();
				currentPage = 1;
				loadSessions(1);
			}, 300);
		});

		initSessionsPanel();

		document.addEventListener('wp-powersuite-modal-loaded', function (event) {
			if (event.detail && event.detail.moduleId === 'login-session-manager') {
				initSessionsPanel();
			}
		});
	});
})(jQuery);
