/* global document, MutationObserver */
(function () {
	'use strict';

	const BODY_CLASS = 'foodord-hide-topping-labels';
	const VALUE_SELECTOR = '[data-foodord-topping-values]';
	let observer = null;

	const hideClassicLabel = (valueEl) => {
		const dd = valueEl.closest('dd');
		if (!dd) {
			return;
		}
		const dt = dd.previousElementSibling;
		if (dt && 'DT' === dt.tagName && dt.getAttribute('data-foodord-label-hidden') !== '1') {
			dt.setAttribute('data-foodord-label-hidden', '1');
			dt.style.display = 'none';
		}
	};

	const hideBlocksLabel = (valueEl) => {
		const valueWrapper = valueEl.closest('.wc-block-components-product-details__value');
		if (!valueWrapper) {
			return;
		}
		const label = valueWrapper.previousElementSibling;
		if (
			label &&
			label.classList &&
			label.classList.contains('wc-block-components-product-details__name') &&
			label.getAttribute('data-foodord-label-hidden') !== '1'
		) {
			label.setAttribute('data-foodord-label-hidden', '1');
			label.style.display = 'none';
		}
	};

	const processValueNode = (valueEl) => {
		if (!valueEl || valueEl.getAttribute('data-foodord-label-processed') === '1') {
			return;
		}
		valueEl.setAttribute('data-foodord-label-processed', '1');
		hideClassicLabel(valueEl);
		hideBlocksLabel(valueEl);
	};

	const scanForValues = () => {
		document.querySelectorAll(VALUE_SELECTOR).forEach(processValueNode);
	};

	const initObserver = () => {
		if (observer) {
			return;
		}
		observer = new MutationObserver((mutations) => {
			if (!mutations || !mutations.length) {
				return;
			}
			scanForValues();
		});
		observer.observe(document.body, { childList: true, subtree: true });
	};

	const init = () => {
		if (!document.body || !document.body.classList.contains(BODY_CLASS)) {
			return;
		}
		scanForValues();
		initObserver();
		document.addEventListener('updated_wc_div', scanForValues);
		document.addEventListener('wc_fragment_refresh', scanForValues);
		document.addEventListener('foodord:cart-refreshed', scanForValues);
	};

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