jQuery(document).ready(function($) {
	var deactivateUrl = null

	function openModal(url) {
		deactivateUrl = url

		$('#posten-bring-deactivate-modal').addClass('visible').attr('aria-hidden', 'false')
		window.dispatchEvent(new CustomEvent('posten-bring-checkout:deactivate:open'))
	}

	function closeModal() {
		$('#posten-bring-deactivate-modal').removeClass('visible').attr('aria-hidden', 'true')

		if (!deactivateUrl) return

		const a = document.createElement('a')
		a.href = deactivateUrl;
		a.dataset.bypass = '1';
		document.body.appendChild(a);
		a.click();
	}

	$(document).on('click', '#close-posten-bring-modal', function () {
		closeModal()
	});

	$(document).on('click', function (event) {
		if (!$(event.target).closest('.posten-bring-custom-modal').length && !$(event.target).is('#deactivate-posten-bring-checkout')) {
			closeModal()
		}
	});

	$(document).on('keydown', function(e){
		if (e.key === 'Escape' && $('#posten-bring-deactivate-modal').attr('aria-hidden') === 'false') {
			e.preventDefault();
			closeModal();
		}
	})

	$('tr[data-slug="posten-bring-checkout"] .deactivate a').on('click', function (e) {
		if (this.dataset.bypass === '1') return
		e.preventDefault();
		const deactivateUrl = $(this).attr('href');
		openModal(deactivateUrl)
	})

	window.addEventListener('posten-bring-checkout:deactivate:continue', closeModal, {});
})
