(function() {
	'use strict';

	var config = window.seovaultseo_redirect || {};
	var i18n = config.i18n || {};
	var msgEl = document.getElementById('seovaultseo-redirect-msg');
	var addBtn = document.getElementById('seovaultseo-redirect-add-btn');

	if (!config.ajax_url || !config.nonce || !addBtn) {
		return;
	}

	function showMessageAt(element, text, state) {
		if (!element) {
			return;
		}
		element.textContent = text || '';
		element.style.color = 'error' === state ? '#d63638' : ('pending' === state ? '#2271b1' : '#00a32a');
	}

	function showMsg(text, isError) {
		showMessageAt(msgEl, text, isError ? 'error' : 'success');
		window.setTimeout(function() { showMessageAt(msgEl, '', 'success'); }, 4000);
	}

	function values() {
		return {
			origin: document.getElementById('seovaultseo-redirect-origin').value.trim(),
			target: document.getElementById('seovaultseo-redirect-target').value.trim(),
			type: document.getElementById('seovaultseo-redirect-type').value,
			format: document.getElementById('seovaultseo-redirect-format').value
		};
	}

	function request(action, data, usesFormData) {
		var body;
		if (usesFormData) {
			body = data;
		} else {
			body = new URLSearchParams(Object.assign({action: action, nonce: config.nonce}, data || {}));
		}
		return fetch(config.ajax_url, {
			method: 'POST',
			headers: usesFormData ? {} : {'Content-Type': 'application/x-www-form-urlencoded'},
			body: body,
			credentials: 'same-origin'
		}).then(function(response) { return response.json(); });
	}

	addBtn.addEventListener('click', function() {
		var data = values();
		if (!data.origin) {
			showMsg(i18n.origin_required, true);
			return;
		}
		var isEdit = Boolean(addBtn.dataset.editId);
		if (isEdit) {
			data.id = addBtn.dataset.editId;
		}
		request(isEdit ? 'seovaultseo_redirect_update' : 'seovaultseo_redirect_add', data)
			.then(function(response) {
				if (response.success) {
					window.location.reload();
					return;
				}
				showMsg((response.data && response.data.message) || (isEdit ? i18n.update_failed : i18n.add_failed), true);
			})
			.catch(function() { showMsg(i18n.request_failed, true); });
	});

	document.addEventListener('click', function(event) {
		var edit = event.target.closest('.seovaultseo-redirect-edit');
		var remove = event.target.closest('.seovaultseo-redirect-delete');
		if (edit) {
			var editRow = edit.closest('tr');
			document.getElementById('seovaultseo-redirect-origin').value = editRow.querySelector('.origin').textContent;
			document.getElementById('seovaultseo-redirect-target').value = editRow.querySelector('.target').textContent;
			document.getElementById('seovaultseo-redirect-type').value = editRow.querySelector('.type').textContent;
			document.getElementById('seovaultseo-redirect-format').value = editRow.querySelector('.format').textContent;
			addBtn.textContent = i18n.update_redirect;
			addBtn.dataset.editId = editRow.dataset.id;
			showMsg(i18n.editing, false);
		}
		if (remove && window.confirm(i18n.confirm_delete)) {
			var row = remove.closest('tr');
			request('seovaultseo_redirect_delete', {id: row.dataset.id})
				.then(function(response) {
					if (response.success) {
						row.remove();
						showMsg(i18n.deleted, false);
					} else {
						showMsg((response.data && response.data.message) || i18n.delete_failed, true);
					}
				})
				.catch(function() { showMsg(i18n.request_failed, true); });
		}
	});

	var selectAll = document.getElementById('seovaultseo-redirect-select-all');
	if (selectAll) {
		selectAll.addEventListener('change', function() {
			document.querySelectorAll('.seovaultseo-redirect-check').forEach(function(checkbox) {
				checkbox.checked = selectAll.checked;
			});
		});
	}

	var bulkBtn = document.getElementById('seovaultseo-redirect-bulk-delete');
	if (bulkBtn) {
		bulkBtn.addEventListener('click', function() {
			var ids = Array.prototype.map.call(document.querySelectorAll('.seovaultseo-redirect-check:checked'), function(checkbox) {
				return checkbox.value;
			});
			if (!ids.length) {
				showMsg(i18n.select_one, true);
				return;
			}
			if (!window.confirm(i18n.confirm_bulk)) {
				return;
			}
			request('seovaultseo_redirect_bulk_delete', {ids: ids.join(',')})
				.then(function(response) {
					if (response.success) {
						window.location.reload();
					} else {
						showMsg((response.data && response.data.message) || i18n.bulk_failed, true);
					}
				})
				.catch(function() { showMsg(i18n.request_failed, true); });
		});
	}

	var importBtn = document.getElementById('seovaultseo-redirect-import-btn');
	var importMsg = document.getElementById('seovaultseo-redirect-import-msg');
	if (importBtn) {
		importBtn.addEventListener('click', function() {
			var fileInput = document.getElementById('seovaultseo-redirect-csv-file');
			if (!fileInput || !fileInput.files.length) {
				showMessageAt(importMsg, i18n.select_csv, 'error');
				return;
			}
			var formData = new FormData();
			formData.append('action', 'seovaultseo_redirect_import_csv');
			formData.append('nonce', config.nonce);
			formData.append('seovaultseo_redirect_csv', fileInput.files[0]);
			importBtn.disabled = true;
			showMessageAt(importMsg, i18n.importing, 'pending');
			request('', formData, true)
				.then(function(response) {
					importBtn.disabled = false;
					if (response.success) {
						showMessageAt(importMsg, response.data.message, 'success');
						window.setTimeout(function() { window.location.reload(); }, 1500);
					} else {
						showMessageAt(importMsg, (response.data && response.data.message) || i18n.import_failed, 'error');
					}
				})
				.catch(function() {
					importBtn.disabled = false;
					showMessageAt(importMsg, i18n.request_failed, 'error');
				});
		});
	}
}());
