(function () {
	'use strict';

	var activeModal = null;
	var activeButton = null;

	function getFocusableElements(container) {
		return Array.prototype.slice.call(
			container.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')
		);
	}

	function openPopup(button) {
		var widget = button.closest('.ea-popup-widget');
		var modal = widget ? widget.querySelector('[data-ea-popup-modal]') : null;

		if (!modal) {
			return;
		}

		activeModal = modal;
		activeButton = button;

		if (typeof modal.showModal === 'function' && !modal.open) {
			modal.showModal();
		} else if (!modal.open) {
			modal.setAttribute('open', '');
		}

		modal.classList.add('is-open');
		modal.setAttribute('aria-hidden', 'false');
		button.setAttribute('aria-expanded', 'true');
		document.body.classList.add('ea-popup-lock');

		var focusable = getFocusableElements(modal);
		if (focusable.length) {
			focusable[0].focus();
		}
	}

	function closePopup(modal) {
		if (!modal) {
			return;
		}

		modal.classList.remove('is-open');
		modal.setAttribute('aria-hidden', 'true');

		if (typeof modal.close === 'function' && modal.open) {
			modal.close();
		} else {
			modal.removeAttribute('open');
		}

		if (activeButton) {
			activeButton.setAttribute('aria-expanded', 'false');
			activeButton.focus();
		}

		document.body.classList.remove('ea-popup-lock');
		activeModal = null;
		activeButton = null;
	}

	function trapFocus(event) {
		if (!activeModal || event.key !== 'Tab') {
			return;
		}

		var focusable = getFocusableElements(activeModal);
		if (!focusable.length) {
			event.preventDefault();
			return;
		}

		var first = focusable[0];
		var last = focusable[focusable.length - 1];

		if (event.shiftKey && document.activeElement === first) {
			event.preventDefault();
			last.focus();
		} else if (!event.shiftKey && document.activeElement === last) {
			event.preventDefault();
			first.focus();
		}
	}

	document.addEventListener('click', function (event) {
		var openButton = event.target.closest('.ea-popup-button');
		var closeButton = event.target.closest('[data-ea-popup-close]');

		if (openButton) {
			event.preventDefault();
			openPopup(openButton);
			return;
		}

		if (closeButton) {
			event.preventDefault();
			closePopup(closeButton.closest('[data-ea-popup-modal]'));
			return;
		}

		if (event.target.matches('[data-ea-popup-modal]')) {
			closePopup(event.target);
		}
	});

	document.addEventListener('keydown', function (event) {
		if (event.key === 'Escape' && activeModal) {
			closePopup(activeModal);
			return;
		}

		trapFocus(event);
	});
})();
