(function () {
	'use strict';

	var panel = document.getElementById('tdssg-log-panel');
	if (!panel || typeof TDSSGLog === 'undefined') {
		return;
	}

	var body = panel.querySelector('.tdssg-log-body');
	var status = panel.querySelector('.tdssg-log-status');
	var refreshButton = panel.querySelector('.tdssg-refresh-log');
	var clearButton = panel.querySelector('.tdssg-clear-log');
	var countdown = panel.querySelector('.tdssg-log-countdown');
	var previousButton = panel.querySelector('.tdssg-page-previous');
	var nextButton = panel.querySelector('.tdssg-page-next');
	var pageStatus = panel.querySelector('.tdssg-page-status');
	var searchInput = panel.querySelector('#tdssg-log-search');
	var searchButton = panel.querySelector('.tdssg-search-log');
	var clearSearchButton = panel.querySelector('.tdssg-clear-search');
	var busy = false;
	var currentPage = 1;
	var currentSearch = '';
	var pageCount = Number(panel.dataset.pages) || 1;
	var interval = Number(TDSSGLog.interval) || 30000;
	var secondsRemaining = Math.ceil(interval / 1000);

	function cell(value, code, className) {
		var td = document.createElement('td');
		var content = value || '-';
		if (className) {
			td.className = className;
		}
		if (code) {
			var codeNode = document.createElement('code');
			codeNode.textContent = content;
			td.appendChild(codeNode);
		} else {
			td.textContent = content;
		}
		return td;
	}

	function render(events) {
		body.replaceChildren();
		if (!events.length) {
			var emptyRow = document.createElement('tr');
			var emptyCell = cell(TDSSGLog.emptyMessage, false);
			emptyCell.colSpan = 7;
			emptyRow.appendChild(emptyCell);
			body.appendChild(emptyRow);
			return;
		}

		events.forEach(function (event) {
			var row = document.createElement('tr');
			row.appendChild(cell(event.time, false));
			row.appendChild(cell(event.network, true));
			row.appendChild(cell(event.reason, false));
			row.appendChild(cell(event.status, false));
			row.appendChild(cell(event.count, false));
			row.appendChild(cell(event.search, false, 'tdssg-search-cell'));
			row.appendChild(cell(event.user_agent, true, 'tdssg-user-agent-cell'));
			body.appendChild(row);
		});
	}

	function request(action, extra) {
		var data = new URLSearchParams();
		data.append('action', action);
		data.append('nonce', TDSSGLog.nonce);
		Object.keys(extra || {}).forEach(function (key) {
			data.append(key, extra[key]);
		});

		return fetch(TDSSGLog.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
			body: data.toString()
		}).then(function (httpResponse) {
			return httpResponse.json().then(function (response) {
				if (!httpResponse.ok || !response.success) {
					throw new Error(response.data && response.data.message ? response.data.message : 'HTTP ' + httpResponse.status);
				}
				return response.data;
			});
		});
	}

	function resetCountdown() {
		secondsRemaining = Math.ceil(interval / 1000);
		countdown.textContent = TDSSGLog.nextRefresh + ' ' + secondsRemaining + 's.';
	}

	function updatePagination(pagination) {
		currentPage = Number(pagination.page) || 1;
		pageCount = Number(pagination.pages) || 1;
		var total = Number(pagination.total) || 0;
		previousButton.disabled = busy || currentPage <= 1;
		nextButton.disabled = busy || currentPage >= pageCount;
		pageStatus.textContent = TDSSGLog.pageLabel + ' ' + currentPage + ' ' + TDSSGLog.ofLabel + ' ' + pageCount + ' (' + total + ' ' + TDSSGLog.eventsLabel + ')';
	}

	function refresh() {
		if (busy || document.hidden) {
			return;
		}

		busy = true;
		resetCountdown();
		refreshButton.disabled = true;
		previousButton.disabled = true;
		nextButton.disabled = true;

		request('tdssg_fetch_events', {
			page_number: currentPage,
			log_search: currentSearch
		}).then(function (data) {
			render(data.events || []);
			updatePagination(data.pagination || {page: 1, pages: 1, total: 0});
			status.textContent = (currentSearch ? TDSSGLog.filteredText + ' ' + currentSearch + '. ' : '') + TDSSGLog.updatedText + ' ' + new Date().toLocaleTimeString();
		}).catch(function (error) {
			status.textContent = error.message || TDSSGLog.errorMessage;
		}).finally(function () {
			busy = false;
			refreshButton.disabled = false;
			previousButton.disabled = currentPage <= 1;
			nextButton.disabled = currentPage >= pageCount;
		});
	}

	refreshButton.addEventListener('click', refresh);
	searchButton.addEventListener('click', function () {
		currentSearch = searchInput.value.trim();
		currentPage = 1;
		clearSearchButton.hidden = !currentSearch;
		refresh();
	});
	searchInput.addEventListener('keydown', function (event) {
		if (event.key === 'Enter') {
			event.preventDefault();
			searchButton.click();
		}
	});
	clearSearchButton.addEventListener('click', function () {
		searchInput.value = '';
		currentSearch = '';
		currentPage = 1;
		clearSearchButton.hidden = true;
		refresh();
	});
	previousButton.addEventListener('click', function () {
		if (!busy && currentPage > 1) {
			currentPage--;
			refresh();
		}
	});
	nextButton.addEventListener('click', function () {
		if (!busy && currentPage < pageCount) {
			currentPage++;
			refresh();
		}
	});
	clearButton.addEventListener('click', function () {
		if (busy || !window.confirm(TDSSGLog.confirmClear)) {
			return;
		}

		busy = true;
		clearButton.disabled = true;
		clearButton.textContent = TDSSGLog.clearingText;

		request('tdssg_clear_events').then(function (data) {
			currentPage = 1;
			render(data.events || []);
			updatePagination(data.pagination || {page: 1, pages: 1, total: 0});
			status.textContent = TDSSGLog.updatedText + ' ' + new Date().toLocaleTimeString();
		}).catch(function (error) {
			status.textContent = error.message || TDSSGLog.errorMessage;
		}).finally(function () {
			busy = false;
			clearButton.disabled = false;
			clearButton.textContent = TDSSGLog.clearText;
		});
	});

	resetCountdown();
	window.setInterval(function () {
		if (document.hidden) {
			return;
		}
		secondsRemaining--;
		if (secondsRemaining <= 0) {
			refresh();
			return;
		}
		countdown.textContent = TDSSGLog.nextRefresh + ' ' + secondsRemaining + 's.';
	}, 1000);
}());

