(() => {
	const modal = document.getElementById('foodord-allergy-info-modal');
	if (!modal) {
		return;
	}

	const dialog = modal.querySelector('.foodord-allergy-info-modal__dialog');
	const closeSelectors = '[data-allergy-close]';
	const globalContentEl = modal.querySelector('.foodord-allergy-info-modal__global-content');
	const productContentEl = modal.querySelector('.foodord-allergy-info-modal__product-content');
	const titleEl = modal.querySelector('.foodord-allergy-info-modal__title');
	const iconEl = modal.querySelector('.foodord-allergy-info-modal__icon');
	let lastFocusedElement = null;
	const productAllergenCache = {};

	const SKELETON_HTML = `
		<div class="foodord-allergy-skeleton">
			<div class="foodord-skeleton foodord-allergy-skeleton__icon"></div>
			<div class="foodord-allergy-skeleton__item">
				<div class="foodord-skeleton foodord-allergy-skeleton__title"></div>
				<div class="foodord-skeleton foodord-allergy-skeleton__text"></div>
				<div class="foodord-skeleton foodord-allergy-skeleton__text foodord-allergy-skeleton__text--short"></div>
			</div>
			<div class="foodord-allergy-skeleton__item">
				<div class="foodord-skeleton foodord-allergy-skeleton__title"></div>
				<div class="foodord-skeleton foodord-allergy-skeleton__text"></div>
				<div class="foodord-skeleton foodord-allergy-skeleton__text foodord-allergy-skeleton__text--short"></div>
			</div>
			<div class="foodord-allergy-skeleton__item">
				<div class="foodord-skeleton foodord-allergy-skeleton__title"></div>
				<div class="foodord-skeleton foodord-allergy-skeleton__text"></div>
			</div>
		</div>
	`;

	// Create and append the loading skeleton element to the content container.
	const loadingEl = document.createElement('div');
	loadingEl.innerHTML = SKELETON_HTML;
	const skeletonContainer = loadingEl.firstElementChild;
	const contentRoot = modal.querySelector('.foodord-allergy-info-modal__content');
	if (contentRoot && skeletonContainer) {
		contentRoot.appendChild(skeletonContainer);
	}

	const setModalVisibility = (isOpen) => {
		if (isOpen) {
			modal.classList.add('is-open');
			modal.setAttribute('aria-hidden', 'false');
		} else {
			modal.classList.remove('is-open');
			modal.setAttribute('aria-hidden', 'true');
		}
	};

	const focusFirstElement = () => {
		const focusTarget = modal.querySelector('.foodord-allergy-info-modal__close') || modal;
		if (focusTarget) {
			focusTarget.focus({ preventScroll: true });
		}
	};

	const showLoading = () => {
		if (skeletonContainer) {
			skeletonContainer.classList.add('is-visible');
		}
		if (globalContentEl) {
			globalContentEl.style.display = 'none';
			globalContentEl.setAttribute('hidden', '');
		}
		if (productContentEl) {
			productContentEl.style.display = 'none';
			productContentEl.setAttribute('hidden', '');
		}
		if (iconEl) {
			iconEl.style.display = 'none';
			iconEl.setAttribute('hidden', '');
		}
	};

	const hideLoading = () => {
		if (skeletonContainer) {
			skeletonContainer.classList.remove('is-visible');
		}
	};

	const showGlobalContent = () => {
		hideLoading();
		if (globalContentEl) {
			globalContentEl.style.display = '';
			globalContentEl.removeAttribute('hidden');
		}
		if (productContentEl) {
			productContentEl.style.display = 'none';
			productContentEl.setAttribute('hidden', '');
			productContentEl.innerHTML = '';
		}
		if (iconEl) {
			iconEl.style.display = '';
			iconEl.removeAttribute('hidden');
		}
		if (titleEl && typeof foodordAllergyInfo !== 'undefined') {
			titleEl.textContent = foodordAllergyInfo.globalTitle || 'Allergy Info';
		}
	};

	const showProductContent = (html) => {
		hideLoading();
		if (globalContentEl) {
			globalContentEl.style.display = 'none';
			globalContentEl.setAttribute('hidden', '');
		}
		if (productContentEl) {
			productContentEl.innerHTML = html;
			productContentEl.style.display = '';
			productContentEl.removeAttribute('hidden');
		}
		if (iconEl) {
			iconEl.style.display = '';
			iconEl.removeAttribute('hidden');
		}
		if (titleEl && typeof foodordAllergyInfo !== 'undefined') {
			titleEl.textContent = foodordAllergyInfo.productTitle || 'Allergen Information';
		}
	};

	const fetchProductAllergens = (productId, callback) => {
		if (productAllergenCache[productId]) {
			callback(productAllergenCache[productId]);
			return;
		}

		if (typeof foodordAllergyInfo === 'undefined' || !foodordAllergyInfo.ajaxUrl) {
			callback(null);
			return;
		}

		const formData = new FormData();
		formData.append('action', 'foodord_get_product_allergens');
		formData.append('nonce', foodordAllergyInfo.nonce);
		formData.append('product_id', productId);

		fetch(foodordAllergyInfo.ajaxUrl, {
			method: 'POST',
			body: formData,
			credentials: 'same-origin',
		})
			.then((response) => response.json())
			.then((data) => {
				if (data.success && data.data && data.data.html) {
					productAllergenCache[productId] = data.data.html;
					callback(data.data.html);
				} else {
					callback(null);
				}
			})
			.catch(() => {
				callback(null);
			});
	};

	const handleOpen = (event, trigger) => {
		if (event) {
			event.preventDefault();
		}
		if (modal.classList.contains('is-open')) {
			return;
		}

		lastFocusedElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;

		// Check if this is a product-specific allergen trigger.
		const hasProductAllergens = trigger && trigger.getAttribute('data-has-product-allergens') === '1';
		const productId = trigger ? trigger.getAttribute('data-product-id') : null;

		if (hasProductAllergens && productId) {
			// Update title immediately to prevent it from changing mid-opening.
			if (titleEl && typeof foodordAllergyInfo !== 'undefined') {
				titleEl.textContent = foodordAllergyInfo.productTitle || 'Allergen Information';
			}

			// If not cached, show loading state and open modal immediately.
			if (!productAllergenCache[productId]) {
				showLoading();
			} else {
				showProductContent(productAllergenCache[productId]);
			}

			setModalVisibility(true);
			document.body.classList.add('foodord-allergy-info-open');
			window.requestAnimationFrame(focusFirstElement);

			if (!productAllergenCache[productId]) {
				fetchProductAllergens(productId, (html) => {
					if (html) {
						showProductContent(html);
					} else {
						showGlobalContent();
					}
				});
			}
		} else {
			showGlobalContent();
			setModalVisibility(true);
			window.requestAnimationFrame(focusFirstElement);
			document.body.classList.add('foodord-allergy-info-open');
		}
	};

	const handleClose = (event) => {
		if (event) {
			event.preventDefault();
		}
		if (!modal.classList.contains('is-open')) {
			return;
		}
		setModalVisibility(false);
		document.body.classList.remove('foodord-allergy-info-open');
		if (lastFocusedElement && typeof lastFocusedElement.focus === 'function') {
			lastFocusedElement.focus({ preventScroll: true });
		}
	};

	const handleDocumentClick = (event) => {
		const trigger = event.target.closest('[data-allergy-trigger="true"]');
		if (trigger) {
			if (event) {
				event.preventDefault();
				event.stopPropagation();
				if (typeof event.stopImmediatePropagation === 'function') {
					event.stopImmediatePropagation();
				}
			}
			handleOpen(event, trigger);
			return;
		}

		if (!modal.classList.contains('is-open')) {
			return;
		}

		if (event.target.closest(closeSelectors)) {
			handleClose(event);
			return;
		}

		if (dialog && !dialog.contains(event.target)) {
			handleClose(event);
		}
	};

	const handleKeydown = (event) => {
		if ('Escape' === event.key && modal.classList.contains('is-open')) {
			handleClose(event);
		}
	};

	document.addEventListener('click', handleDocumentClick, true);
	document.addEventListener('keydown', handleKeydown);
})();


