if (document.readyState === 'loading') {
	document.addEventListener('DOMContentLoaded', () => {
		init()
	})
} else {
	init()
}

function init() {
	const checkoutTable = document.getElementById('order_review') ||
		document.getElementById('dintero-checkout-order-review') ||
		document.getElementById('kco-order-review') ||
		document.getElementById('dibs-order-review');
	const cartTable = document.getElementsByClassName('cart-collaterals');
	const pickupPointContainer = document.getElementById('posten-bring-checkout-pp-shadow-container');
	const generalContainer = document.getElementById('posten-bring-checkout-general-shipping-option-shadow-container');
	const homeDeliveryContainer = document.getElementById('posten-bring-checkout-hd-shadow-container');
	const observer = new MutationObserver((mutations, observer) => {
		for (const mutation of  mutations) {
			for (const node of mutation.addedNodes) {
				const ppContainer = document.getElementById('posten-bring-checkout-pp-shadow-container');
				const gContainer = document.getElementById('posten-bring-checkout-general-shipping-option-shadow-container');
				const hdContainer = document.getElementById('posten-bring-checkout-hd-shadow-container');
				if (ppContainer && ! ppContainer.shadowRoot) {
					attachShadowDom(ppContainer, pickupPointHandler, '#posten-bring-checkout-pickup-points');
				} else if (gContainer && ! gContainer.shadowRoot) {
					attachShadowDom(gContainer);
				} else if (hdContainer && ! hdContainer.shadowRoot) {
					attachShadowDom(hdContainer, deliveryDateHandler, '#posten-bring-checkout-delivery-dates');
				}
			}
		}
	});

	if (checkoutTable) {
		observer.observe(checkoutTable, { childList: true, subtree: true });
		attachShadowDom(pickupPointContainer, pickupPointHandler, '#posten-bring-checkout-pickup-points');
		attachShadowDom(generalContainer);
		attachShadowDom(homeDeliveryContainer, deliveryDateHandler, '#posten-bring-checkout-delivery-dates');
	}

	if (cartTable.length === 1) {
		observer.observe(cartTable[0], { childList: true, subtree: true});
		attachShadowDom(pickupPointContainer, pickupPointHandler, '#posten-bring-checkout-pickup-points');
		attachShadowDom(generalContainer);
		attachShadowDom(homeDeliveryContainer, deliveryDateHandler, '#posten-bring-checkout-delivery-dates');
	}
}

function attachShadowDom(container, handler, handle) {
	if (container) {
		const content = container.innerHTML

		const shadowRoot = container.attachShadow({mode: 'open'})
		shadowRoot.innerHTML = `<link rel="stylesheet" href="${PostenBringCheckout.cssUrl}">` + content;
		const modalContainer = document.getElementById('posten-bring-checkout-modal')
		let detachedShadow

		if (handler && handle) {
			const modal = shadowRoot.querySelector(handle)
			if (!modalContainer || !modalContainer.shadowRoot) {
				const detachedShadowHost = document.createElement('div')
				detachedShadowHost.id = 'posten-bring-checkout-modal'
				detachedShadowHost.style.all = 'unset'
				document.body.appendChild(detachedShadowHost)
				detachedShadow = detachedShadowHost.attachShadow({ mode: 'open'})
			} else {
				detachedShadow = modalContainer.shadowRoot
			}

			if (modal) {
				const modalOverlay = document.getElementById('posten-bring-checkout-overlay')
				const dark = !!shadowRoot.querySelector('.dark')
				detachedShadow.innerHTML = `<link rel="stylesheet" href="${PostenBringCheckout.cssUrl}">`
				const contentContainer = document.createElement('div')
				contentContainer.className = `posten-bring-checkout-container${dark ? ' dark' : ''}`
				contentContainer.appendChild(modal)
				detachedShadow.appendChild(contentContainer)
				if (!modalOverlay) {
					const overlay = document.createElement('div')
					overlay.id = 'posten-bring-checkout-overlay'
					detachedShadow.appendChild(overlay)
				}
			}

			if (handler && shadowRoot && detachedShadow) {
				handler(shadowRoot, detachedShadow)

				const overlay = detachedShadow.getElementById('posten-bring-checkout-overlay')
				if (overlay) {
					overlay.onclick = function () {
						toggleSelector(detachedShadow, handle)
					}
				}
			}
		}
		container.innerHTML = '';
	}
}

function deliveryDateHandler(shadowRoot, detachedShadowRoot) {
	const chooseDeliveryDate = shadowRoot.querySelector('#choose-delivery-date');
	const hiddenFormField = document.getElementById('posten-bring-checkout-selected-delivery-date');
	const hiddenShippingDateField = document.getElementById('posten-bring-checkout-selected-shipping-date');
	const closeButton = detachedShadowRoot.querySelector('#posten-bring-checkout-close');
	if (chooseDeliveryDate) {
		chooseDeliveryDate.onclick = function() {
			toggleSelector(detachedShadowRoot, '#posten-bring-checkout-delivery-dates');
		}
	}

	if (closeButton) {
		closeButton.onclick = function() {
			toggleSelector(detachedShadowRoot, '#posten-bring-checkout-delivery-dates')
		}
	}

	detachedShadowRoot.querySelectorAll('.radio__checkmark').forEach(dd => dd.onclick = function() {
		shadowRoot.querySelector('#hd-delivery-date').textContent = dd.getAttribute('data-description');
		sessionStorage.setItem('selectedDeliveryDate', dd.getAttribute('value'));
		sessionStorage.setItem('selectedShippingDate', dd.getAttribute('data-shipping-date'));
		hiddenFormField.value = dd.getAttribute('value');
		hiddenShippingDateField.value = dd.getAttribute('data-shipping-date');
		toggleSelector(detachedShadowRoot, '#posten-bring-checkout-delivery-dates');
	})

	const selected = shadowRoot.querySelector('#alt_'+sessionStorage.getItem('selectedDeliveryDate'));
	if (selected) {
		hiddenFormField.value = sessionStorage.getItem('selectedDeliveryDate');
		hiddenShippingDateField.value = sessionStorage.getItem('selectedShippingDate')
		selected.click();
		toggleSelector(detachedShadowRoot, '#posten-bring-checkout-delivery-dates');
	}
}

function pickupPointHandler(shadowRoot, detachedShadowRoot) {
	const choosePickupPoint = shadowRoot.querySelector('#choose-pickup-point');
	const hiddenFormField = document.getElementById('posten-bring-checkout-selected-pickuppoint');
	if (choosePickupPoint) {
		choosePickupPoint.onclick = function() {
			toggleSelector(detachedShadowRoot, '#posten-bring-checkout-pickup-points');
		}

		const closeButton = detachedShadowRoot.querySelector('#posten-bring-checkout-close');

		if (closeButton) {
			closeButton.onclick = function() {
				toggleSelector(detachedShadowRoot, '#posten-bring-checkout-pickup-points')
			}
		}

		detachedShadowRoot.querySelectorAll('.radio__checkmark').forEach(pp => pp.onclick = function() {
			shadowRoot.querySelector('#pp-name').textContent = pp.getAttribute('data-display-name');
			if (pp.getAttribute('data-description')) {
				shadowRoot.querySelector('#pp-description').textContent = pp.getAttribute('data-description');
			}
			shadowRoot.querySelector('#pp-address').textContent = pp.getAttribute('data-address');
			shadowRoot.querySelector('#pp-opening-hours').textContent = pp.getAttribute('data-opening-hours');
			const distance = shadowRoot.querySelector('#pp-distance')
			if (distance) {
				distance.textContent = pp.getAttribute('data-distance');
			}
			const pickupPointId = pp.getAttribute('value');
			sessionStorage.setItem('selectedPickupPointId', pickupPointId);
			hiddenFormField.value = pickupPointId;
			toggleSelector(detachedShadowRoot, '#posten-bring-checkout-pickup-points');
		})

		const selected = shadowRoot.querySelector('#pp_'+sessionStorage.getItem('selectedPickupPointId'));
		if (selected) {
			hiddenFormField.value = sessionStorage.getItem('selectedPickupPointId');
			selected.click();
			toggleSelector(detachedShadowRoot, '#posten-bring-checkout-pickup-points');
		}

		const morePickupPoints = detachedShadowRoot.querySelector('#posten-bring-checkout-more');
		if (morePickupPoints) {
			morePickupPoints.onclick = function() {
				detachedShadowRoot.querySelector('#posten-bring-checkout-pickup-points').classList.remove('hidden');
				detachedShadowRoot.querySelectorAll('.posten-bring-checkout-radio').forEach(element => element.classList.remove('hidden'));
				morePickupPoints.style.display = 'none';
			}
		}
	}
}

function toggleSelector(shadowRoot, id) {
	const selector = shadowRoot.querySelector(id);
	const overlay = shadowRoot.querySelector('#posten-bring-checkout-overlay');
	if (overlay) {
		overlay.style.display = selector.style.display === 'none' ? 'block' : 'none';
	}
	selector.style.display = selector.style.display === 'none' ? 'block' : 'none';
}
