(function () {
	'use strict';

	function getList(root) {
		return root ? root.querySelector('[data-menu-order-list]') : null;
	}

	function moveItem(item, direction) {
		var list = item && item.parentElement;

		if (!list || !item) {
			return;
		}

		if ('up' === direction && item.previousElementSibling) {
			list.insertBefore(item, item.previousElementSibling);
			return;
		}

		if ('down' === direction && item.nextElementSibling) {
			list.insertBefore(item.nextElementSibling, item);
		}
	}

	function initList(list) {
		var dragging = null;

		list.addEventListener('dragstart', function (event) {
			var item = event.target.closest('[data-menu-order-item]');

			if (!item || !list.contains(item)) {
				return;
			}

			dragging = item;
			item.classList.add('is-dragging');
			event.dataTransfer.effectAllowed = 'move';
			event.dataTransfer.setData('text/plain', item.querySelector('input[name="menu_order[]"]')?.value || '');
		});

		list.addEventListener('dragend', function () {
			if (dragging) {
				dragging.classList.remove('is-dragging');
				dragging = null;
			}
		});

		list.addEventListener('dragover', function (event) {
			if (!dragging) {
				return;
			}

			event.preventDefault();
			var target = event.target.closest('[data-menu-order-item]');

			if (!target || target === dragging || !list.contains(target)) {
				return;
			}

			var rect = target.getBoundingClientRect();
			var after = event.clientY > rect.top + rect.height / 2;

			if (after) {
				list.insertBefore(dragging, target.nextElementSibling);
			} else {
				list.insertBefore(dragging, target);
			}
		});
	}

	function initMenuOrder(root) {
		var scope = root || document;
		var lists = scope.querySelectorAll('[data-menu-order-list]');

		lists.forEach(initList);

		scope.addEventListener('click', function (event) {
			var button = event.target.closest('[data-menu-order-action]');

			if (!button) {
				return;
			}

			var item = button.closest('[data-menu-order-item]');

			if (!item) {
				return;
			}

			event.preventDefault();
			moveItem(item, button.getAttribute('data-menu-order-action'));
		});
	}

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