import Splide from "@splidejs/splide";
import { __ } from "@wordpress/i18n";
import convert from "convert-units";
import apiFetch from "@wordpress/api-fetch";
import dashboardPortal from "./dashboard-portal";

jQuery(document).ready(function ($) {
	// unit conversion
	if (delicious_recipes.global_settings.displayUnitConversion && delicious_recipes.global_settings.displayUnitConversion.length > 0 && 'yes' === delicious_recipes.global_settings.displayUnitConversion[0]) {
		const defaultUnitSystem = delicious_recipes.global_settings.defaultUnitSystem;
		const singleRecipe = document.querySelector(".dr-single-recipe");
		if (singleRecipe) {
			const postId = singleRecipe.dataset.id;
			const servingType = delicious_recipes.global_settings.adjustableServingType;

			let servingValue = document.querySelector(".dr-ingredients-scale")?.getAttribute("data-serving-value");
			let DefaultValues = null;
			let originalValues = [];
			let scaleValue = servingValue;

			function updateRecipeData() {
				getRecipeData().then((data) => {
					const recipeConversion = data.recipeUnitConversion;
					if (recipeConversion.length > 0) {
						let unitIndex = 0;
						let supportedUnits = convert().list();
						supportedUnits = supportedUnits.map((unit) => unit.abbr);
						const ingredientLists = document.querySelectorAll(".dr-ingredients-list .dr-unordered-list li");
						ingredientLists.forEach((ingredientList) => {
							const ingredient = ingredientList.querySelector(".ingredient_quantity");
							let unit = ingredientList.querySelector(".ingredient_unit").innerText;
							let conversionUnit = unit.toLowerCase() === 'tbsp' ? 'Tbs' : unit;
							let quantity = fractionToFloat(ingredient.innerText);
							let originalValueExists = originalValues.some(originalValue => originalValue.ingredientList === ingredientList);
							if (!originalValueExists) {
								originalValues.push({ ingredientList, unit, quantity });
							}
							if (conversionUnit) {
								ingredientList.querySelector(".ingredient_unit").innerText = recipeConversion[unitIndex].convertedUnit;
								let convertedAmount = 'scale' === servingType ? (recipeConversion[unitIndex].convertedAmount * scaleValue) : (recipeConversion[unitIndex].convertedAmount / servingValue) * scaleValue;
								convertedAmount = Math.round((convertedAmount + Number.EPSILON) * 100) / 100;
								ingredientList.querySelector(".ingredient_quantity").innerText = convertedAmount > 0 ? convertedAmount : '';
								unitIndex++;
							}
						});
					}
				});
			}

			async function getRecipeData() {
				const recipeData = await apiFetch({ path: '/deliciousrecipe/v1/recipe/' + postId });
				DefaultValues = recipeData.data.recipe_metas;
				if ("" !== DefaultValues) {
					return DefaultValues;
				}
			}

			let unitConversionWrapper = document.querySelector(".dr-ingredients-list .dr-unit-conversion-wrapper");
			if (unitConversionWrapper) {
				if ('scale' === delicious_recipes.global_settings.adjustableServingType) {
					scaleValue = document.querySelector(".dr-ingredients-scale .scale-btn-wrapper .active").getAttribute("data-scale");
					document.addEventListener("click", function (e) {
						if (e.target.matches('[data-scale]')) {
							const currentUnitSystem = document.querySelector(".dr-ingredients-list .dr-unit-conversion-wrapper input:checked");
							scaleValue = e.target.getAttribute('data-scale');
							if (defaultUnitSystem !== currentUnitSystem.value) {
								updateRecipeData();
							}
						}
					});
				} else {
					["keyup", "mouseup"].forEach((event) => {
						document.addEventListener(event, function (e) {
							if (e.target.matches(".dr-scale-ingredients")) {
								const currentUnitSystem = document.querySelector(".dr-ingredients-list .dr-unit-conversion-wrapper input:checked");
								scaleValue = document.querySelector(".dr-scale-ingredients").value;
								if (defaultUnitSystem !== currentUnitSystem.value) {
									updateRecipeData();
								}
							}
						});
					});
				}
			}

			const currentUnitSystems = document.querySelectorAll(".dr-ingredients-list .dr-unit-conversion-wrapper input");
			currentUnitSystems.forEach((unit) => {
				unit.addEventListener("change", function () {
					if (defaultUnitSystem !== this.value) {
						updateRecipeData();
					} else {
						originalValues.forEach(({ ingredientList, unit, quantity }) => {
							setTimeout(() => {
								ingredientList.querySelector(".ingredient_unit").innerText = unit;
								let convertedAmount = 0 !== quantity ? ('scale' === servingType ? (quantity * scaleValue) : ((quantity / servingValue) * scaleValue)) : '';
								convertedAmount = Math.round((convertedAmount + Number.EPSILON) * 100) / 100;
								ingredientList.querySelector(".ingredient_quantity").innerText = convertedAmount > 0 ? convertedAmount : '';
							}, 250);
						});
					}
				});
			});
		}
	}

	const fractionToFloat = (fraction) => {
		if (!fraction) {
			return 0;
		}
		let float = 0;
		if (fraction.includes('⁄')) {
			fraction = fraction.replace('⁄', '/');
		}
		if (fraction.includes('/')) {
			let parts = fraction.split(' ');
			if (parts.length > 1) {
				let whole = parts[0];
				let frac = parts[1];
				let fracParts = frac.split('/');
				float = parseFloat(whole) + (parseFloat(fracParts[0]) / parseFloat(fracParts[1]));
			} else {
				let fracParts = fraction.split('/');
				float = parseFloat(fracParts[0]) / parseFloat(fracParts[1]);
			}
			float = parseFloat(float.toFixed(2));
		} else {
			float = fraction;
		}
		return float;
	}

	$(window).scroll(function () {
		if ($(window).scrollTop() > 500) {
			$(".dr-floating-menu-wrapper").addClass("dr-floating-visible");
		} else {
			$(".dr-floating-menu-wrapper").removeClass("dr-floating-visible");
		}
	});
});

function recipeProScripts() {
	// check if delicious_recipes.global_settings is an object
	let enableRecaptchaForComments = delicious_recipes.global_settings.enableRecaptchaForComments;
	let recaptchaSiteKey = delicious_recipes.global_settings.recaptchaSiteKey;
	let recaptchaSecretKey = delicious_recipes.global_settings.recaptchaSecretKey;
	let recaptchaVersion = delicious_recipes.global_settings.recpatchaVersion;
	let recaptchaResponse = '';
	let recaptchaDiv = document.querySelector('.g-recaptcha');
	let cookiesConsent = document.querySelector('.comment-form-cookies-consent');

	if (recaptchaDiv && cookiesConsent) {
		cookiesConsent.insertAdjacentElement('afterend', recaptchaDiv);
	}
	if (typeof delicious_recipes.global_settings === 'object') {
		// reCAPTCHA for comments form
		enableRecaptchaForComments = delicious_recipes.global_settings.enableRecaptchaForComments;
		recaptchaSiteKey = delicious_recipes.global_settings.recaptchaSiteKey;
		recaptchaSecretKey = delicious_recipes.global_settings.recaptchaSecretKey;
		recaptchaVersion = delicious_recipes.global_settings.recpatchaVersion;
	}
	var drCommentArea = document.querySelector('.dr-comment-area');
	if (drCommentArea) {
		commentForm(drCommentArea);
	}
	delicious_recipes.utilities.on("click", ".dr-form-tab-btn", function () {
		var siblings = this.parentNode.querySelectorAll(".dr-form-tab-btn");
		var grandParent = this.closest(".dr-comment-form");
		var forms = grandParent.querySelectorAll(
			".dr-comment-type-content > div"
		);
		var targetId = grandParent.querySelector(this.dataset.target);
		forms.forEach(function (form) {
			form.style.display = "none";
		});
		siblings.forEach(function (btn) {
			btn.classList.remove("active");
		});
		targetId.style.display = "block";
		this.classList.add("active");
	});

	delicious_recipes.utilities.on("click", ".comment-reply-link", function () {
		var replyParent = this.closest("li");
		var targetForm = this.dataset.respondelement;
		var formElement = replyParent.querySelector("#" + targetForm);
		var cancelReply = formElement.querySelector("span");
		var cancelReplyButton = cancelReply.querySelector("small");
		var elementsToHide = formElement.querySelectorAll('.comment-form-rating, .dr-tags, .did-you-make-recipe, .would-you-recommend-recipe');
		elementsToHide.forEach(function (element) {
			element.style.display = 'none';
		});

		var ratingInput = formElement.querySelector('input[name="rating"]');
		if (ratingInput) {
			ratingInput.remove();
		}
		replyParent.querySelector("#" + targetForm).style.display = "block";
		cancelReplyButton.addEventListener('click', function () {
			elementsToHide.forEach(function (element) {
				element.style.display = '';
			});
			if (ratingInput) {
				formElement.appendChild(ratingInput);
			}
		});

		//Handle recaptcha for reply forms
		if (formElement.id.includes('dr-comment-qa')) {
			formElement.addEventListener('submit', handleSubmitQuestion);
		} else {
			formElement.addEventListener('submit', handleSubmitReview);
		}

		// Handle reply to question form
		let replyButton = this.parentElement;
		let replyClass = replyButton.classList.contains('question') ? 'question' : 'review';
		if (replyClass === 'question') {
			let commentParent = formElement.querySelector('input[name="comment_parent"]');
			commentParent.value = this.dataset.commentid;
			const replyTitle = document.querySelectorAll('.comment-reply-title');

			const parentElement = this.parentElement.parentElement.parentElement;
			const commentHeader = parentElement.querySelector('.dr-comment-header');
			const commentHeaderName = commentHeader.querySelector('.dr-comment-avatar-name').innerText;

			replyTitle.forEach((title) => {
				const cancelLink = title.querySelector('a');
				if (title.classList.contains('question')) {
					if (cancelLink) {
						cancelLink.style.display = 'inline';
					}
					const textElement = title.childNodes[0]; // This is the "Add a question" text node
					if (textElement && textElement.nodeType === Node.TEXT_NODE) {
						textElement.nodeValue = `Ask to ${commentHeaderName}`; // Replace with your desired text
					}
				}
			});
		}

	});

	function handleSubmitReview(e) {
		if ('yes' == enableRecaptchaForComments[0] && recaptchaSiteKey && recaptchaSecretKey) {
			validateRecaptcha(0).then((result) => {
				if (!result) {
					e.preventDefault();
					showError(__('Please verify that you are not a robot.', 'delicious-recipes-pro'), e.target.querySelector('.form-submit'));
				}
			});
		}
	}

	function handleSubmitQuestion(e) {
		if ('yes' == enableRecaptchaForComments[0] && recaptchaSiteKey && recaptchaSecretKey) {
			validateRecaptcha(1).then((result) => {
				if (!result) {
					e.preventDefault();
					showError(__('Please verify that you are not a robot.', 'delicious-recipes-pro'), e.target.querySelector('.form-submit'));
				}
			});
		}
	}

	function showError(message, element) {
		var errorElement = document.createElement('span');
		errorElement.className = 'dr-tooltip';
		var strong = document.createElement('strong');
		var text = document.createTextNode(message);
		strong.appendChild(text);
		errorElement.appendChild(strong);
		element.insertAdjacentElement('beforebegin', errorElement);
		setTimeout(function () {
			errorElement.remove();
		}, 4000);
	}

	// check if reCAPTCHA is enabled
	if (enableRecaptchaForComments && 'yes' == enableRecaptchaForComments[0] && recaptchaSiteKey && recaptchaSecretKey) {
		const script = document.createElement('script');
		if (recaptchaVersion === 'v3') {
			script.src = `https://www.google.com/recaptcha/api.js?render=${recaptchaSiteKey}`;
		} else if (recaptchaVersion === 'v2') {
			script.src = `https://www.google.com/recaptcha/api.js`;
		}
		script.async = true;
		script.defer = true;
		document.body.appendChild(script);
	}

	const validateRecaptcha = async (index) => {
		if ('v3' == recaptchaVersion) {
			recaptchaResponse = await grecaptcha.ready(() => {
				grecaptcha.execute(recaptchaSiteKey, { action: 'submit' }).then((token) => {
					return token;
				});
			})
		} else {
			recaptchaResponse = grecaptcha.getResponse(index);
		}

		if (recaptchaResponse.length === 0) {
			return false;
		} else {
			const response = await apiFetch({
				path: '/deliciousrecipe/v1/recipe-recaptcha-comments',
				method: 'POST',
				data: {
					recaptchaResponse: recaptchaResponse,
					googleSecretKey: recaptchaSecretKey
				}
			});
			if (response.success) {
				if (response.data.success) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
	}

	function updatedReviewForm(element = null) {
		const root = element || document;

		// recaptcha for comments form
		const reviewForms = root.querySelector('.dr-comment-review');
		const questionForms = root.querySelector('.dr-comment-qa');

		if (reviewForms) {
			reviewForms.addEventListener('submit', handleSubmitReview);
		}

		if (questionForms) {
			questionForms.addEventListener('submit', handleSubmitQuestion);
		}

		// handling input value for "Did you make this recipe?" question
		const yesButtonMake = root.getElementById('did-make-recipe-yes');
		const noButtonMake = root.getElementById('did-make-recipe-no');
		const didMakeRecipeInput = root.getElementById('did-make-recipe');
		const uploadImageOptions = root.querySelector('.dr-form-field');

		if (yesButtonMake && noButtonMake && didMakeRecipeInput) {
			yesButtonMake.addEventListener('click', function () {
				didMakeRecipeInput.value = 'yes';
				if (uploadImageOptions) uploadImageOptions.style.display = 'block';
			});
			noButtonMake.addEventListener('click', function () {
				didMakeRecipeInput.value = 'no';
				if (uploadImageOptions) uploadImageOptions.style.display = 'none';
			});
		}

		// handling input value for "Would you recommend this recipe?" question
		const yesButtonRecommend = root.getElementById('would-recommend-recipe-yes');
		const noButtonRecommend = root.getElementById('would-recommend-recipe-no');
		const wouldRecommendRecipeInput = root.getElementById('would-recommend-recipe');

		if (yesButtonRecommend && noButtonRecommend && wouldRecommendRecipeInput) {
			yesButtonRecommend.addEventListener('click', function () {
				wouldRecommendRecipeInput.value = 'yes';
			});
			noButtonRecommend.addEventListener('click', function () {
				wouldRecommendRecipeInput.value = 'no';
			});
		}

		// Show/hide tags based on "Show More" button click
		const tagsContainer = root.querySelector('.dr-tags');
		const showMore = root.getElementById('dr-show-more');
		const tags = root.getElementById('tags');
		if (tagsContainer && tags && showMore) {
			const tagItems = tags.querySelectorAll('a');
			const maxVisibleTags = 6;

			tagItems.forEach((tag, index) => {
				if (index >= maxVisibleTags) {
					tag.style.display = 'none';
				}
			});

			if (tagItems.length > maxVisibleTags) {
				showMore.classList.add('visible');
			}

			showMore.addEventListener('click', function () {
				tags.classList.toggle('expanded');
				if (tags.classList.contains('expanded')) {
					showMore.textContent = __('Show Less', 'delicious-recipes-pro');
					tagItems.forEach(tag => tag.style.display = '');
				} else {
					showMore.textContent = __('Show More', 'delicious-recipes-pro');
					tagItems.forEach((tag, index) => {
						if (index >= maxVisibleTags) {
							tag.style.display = 'none';
						}
					});
				}
			});

			// Handle recipe tags
			let selectedTags = [];
			const recipeTagsInput = root.getElementById('recipe-tags');
			tagItems.forEach(tag => {
				tag.addEventListener('click', function () {
					const tagText = this.getAttribute('data-tag');
					if (selectedTags.includes(tagText)) {
						selectedTags = selectedTags.filter(t => t !== tagText);
						this.classList.remove('selected');
					} else {
						selectedTags.push(tagText);
						this.classList.add('selected');
					}
					recipeTagsInput.value = selectedTags;
				});
			});
		}

		// Handle the comment section in the header of the page to open a popup
		const commentPopUp = root.querySelector('.dr-comment-popup');
		const ratingsWrapper = root.querySelector('.dr-star-ratings-wrapper');
		const reviewBoxArea = root.getElementById('respond');
		if (commentPopUp) {
			commentPopUp.addEventListener('click', function () {
				reviewBoxArea.scrollIntoView({ behavior: "smooth" });
			});
		}
		if (ratingsWrapper) {
			ratingsWrapper.addEventListener('click', function () {
				reviewBoxArea.scrollIntoView({ behavior: "smooth" });
			});
		}

		// Handle when users leave the page
		const enableExitIntent = delicious_recipes.global_settings.enableExitIntent;
		if (root.querySelector(".dr-single-recipe") && enableExitIntent && 'yes' === enableExitIntent[0]) {
			const postId = root.querySelector(".dr-single-recipe").dataset.id;
			let notFound = false;
			const getIPAddress = async () => {
				try {
					const response = await fetch('https://api.ipify.org?format=json');
					const data = await response.json();
					return data.ip;
				} catch (error) {
					console.error('Error fetching IP address:', error);
					return null;
				}
			};

			const fetchData = async () => {
				let usersIPAddress = await getIPAddress();
				if (usersIPAddress) {
					apiFetch({
						path: '/deliciousrecipe/v1/exit-intent',
						method: 'POST',
						data: { post_id: postId, ip: usersIPAddress }
					}).then((response) => {
						if (response.success && !response.data) {
							notFound = true;
						}
					});
				}
			};

			fetchData();

			document.addEventListener('mouseleave', () => {
				let reviewShown;
				if (notFound) {
					let lastShown = localStorage.getItem('reviewShown' + postId);
					if (lastShown) {
						let reviewShownData = JSON.parse(lastShown);
						if (reviewShownData.post_id === postId && (Date.now() - reviewShownData.date) < 24 * 60 * 60 * 1000) {
							reviewShown = true;
						}
					}

					let modalOverlay = root.querySelector('.wpd-modal-overlay');
					if (!modalOverlay && !reviewShown) {
						showReviewModal(reviewBoxArea);
						const reviewShownData = {
							'date': Date.now(),
							'post_id': postId
						};
						localStorage.setItem('reviewShown' + postId, JSON.stringify(reviewShownData));
					}
				}
			});
		}

		// Remove double comment form when Elementor support toggle is enabled
		const commentSection = root.querySelectorAll('.dr-pro-comment-section');
		const enableElementorSupport = delicious_recipes.global_settings.enableElementorSupport;
		if (enableElementorSupport && 'yes' === enableElementorSupport[0] && commentSection.length > 1) {
			commentSection[1].remove();
		}
	}

	// Handle the rating form and rating label in the comment section
	function reviewFormRating(element = null) {
		const root = element || document;
		const reviewForm = root.querySelector('.comment-respond');
		if (reviewForm && delicious_recipes.license_validity) {
			const ratingLabel = {
				1: __("Couldn't eat it", 'delicious-recipes-pro'),
				2: __("Didn't like it", 'delicious-recipes-pro'),
				3: __("It was OK", 'delicious-recipes-pro'),
				4: __("Liked it", 'delicious-recipes-pro'),
				5: __("Loved it", 'delicious-recipes-pro')
			};
			const enableRatings = delicious_recipes.global_settings.enableRatings;
			if (enableRatings.length > 0) {
				const ratingBoxArea = reviewForm.querySelector('.comment-form-rating');
				if (ratingBoxArea) {
					const ratingSets = ratingBoxArea.querySelector('.wpd-rating-container');
					const stars = ratingSets.querySelectorAll('.star');
					const ratingValueWord = ratingBoxArea.querySelector('.rating-value-word');
					const ratingWithoutComment = root.querySelector('.rating-without-comment');
					const ratingWithoutCommentStars = ratingWithoutComment.querySelectorAll('.star');

					//Due to custom rating.js file, we need to remove the second input field especially during autoload recipes
					if (ratingBoxArea.querySelectorAll('input[name="rating"]').length > 1) {
						ratingBoxArea.querySelectorAll('input[name="rating"]')[1].remove();
					}
					const ratingInput = ratingBoxArea.querySelector('input[name="rating"]');

					let selectedRating = ratingSets.dataset.dynamicRating;
					ratingWithoutCommentStars.forEach((star, index) => {
						star.addEventListener('click', function () {
							let rating = index + 1;
							ratingSets.dataset.dynamicRating = rating;
							ratingInput.value = rating;
							selectedRating = rating;
							stars.forEach(star => star.querySelector('path').setAttribute('fill', 'none'));
							for (let i = 1; i <= rating; i++) {
								stars[i - 1].querySelector('path').setAttribute('fill', '#FFAE34');
							}
						});
					});

					stars.forEach((star, index) => {
						const ratingContainer = star.closest('.wpd-rating-container');
						star.addEventListener('mouseover', function () {
							ratingValueWord.innerHTML = ratingLabel[ratingContainer.dataset.dynamicRating];
						});
						star.addEventListener('mouseout', function () {
							if (ratingInput.value) {
								ratingValueWord.innerHTML = ratingLabel[ratingInput.value];
								stars.forEach(star => star.querySelector('path').setAttribute('fill', 'none'));
								for (let i = 1; i <= ratingInput.value; i++) {
									stars[i - 1].querySelector('path').setAttribute('fill', '#FFAE34');
								}
							} else {
								ratingValueWord.innerHTML = ratingLabel[ratingContainer.dataset.dynamicRating];
							}
						});
						star.addEventListener('click', function () {
							ratingInput.value = ratingContainer.dataset.dynamicRating;
						});
					});
				}
			}
		}
	}

	function ratingWithoutReview(element = null) {
		const root = element || document;
		const wrapper = root.querySelector(".rating-without-comment");
		if (wrapper) {
			const recipeCardRatingAvg = root.querySelector('.dr-recipe-summary-inner .dr-rating.dr-star-ratings-wrapper');
			// const reviewBoxArea = document.getElementById('respond');
			const reviewBoxArea = root.querySelector('.comment-respond');
			const labelString = wrapper.getAttribute('data-label');

			if (recipeCardRatingAvg) {
				jQuery(recipeCardRatingAvg).append(`<span class="dr-rating-tooltip">${labelString}</span>`);
				recipeCardRatingAvg.setAttribute('style', 'cursor:pointer;')
				recipeCardRatingAvg.addEventListener('click', function () {
					showReviewModal(reviewBoxArea);
				});
			}

			root.getElementById('rating-without-comment-container').addEventListener('click', function (e) {
				reviewBoxArea.scrollIntoView({
					behavior: "smooth"
				});
			});
		}
	}

	function showReviewModal(reviewBoxArea) {
		const originalParent = reviewBoxArea.parentNode;
		const modalOverlay = document.createElement('div');
		const modal = document.createElement('div');
		modalOverlay.classList = 'wpd-modal-overlay';
		modal.id = 'reviewModal';
		modal.classList = 'wpd-modal';

		modal.innerHTML = `
			<button type="button" id="closeModal" class="wpd-modal-close">Close</button>
		`;

		modal.appendChild(reviewBoxArea);
		modalOverlay.appendChild(modal);

		document.body.appendChild(modalOverlay);

		reviewBoxArea.addEventListener('submit', handleSubmitReview);

		const removeModal = () => {
			modalOverlay.classList.add('fade-out');
			setTimeout(() => {
				modalOverlay.classList.remove('fade-out');
				originalParent.appendChild(reviewBoxArea);
				document.body.removeChild(modalOverlay);
			}, 300);
		}

		document.getElementById('closeModal').addEventListener('click', function () {
			removeModal();
		});
		modalOverlay.addEventListener('click', function (e) {
			if (!modal.contains(e.target)) {
				removeModal();
			}
		})
	}

	drCustomTab(document, ".dr-comment-list-btn");

	// custom tab function
	function drCustomTab(parent, tabBtn) {
		var tabBtns = parent.querySelectorAll(tabBtn);
		if (tabBtns) {
			tabBtns.forEach(function (tabBtn) {
				var targetId = tabBtn.dataset.target;
				if (parent.querySelector(targetId)) {
					parent.querySelector(targetId).style.display = "none";
				}
				if (tabBtn.classList.contains("active")) {
					var activeTab = tabBtn.dataset.target;
					if (parent.querySelector(activeTab)) {
						parent.querySelector(activeTab).style.display = "block";
					}
				}
			});
		}
		parent.addEventListener("click", function (el) {
			if (el.target.matches(tabBtn)) {
				var btnParent = el.target.parentNode;
				var btns = btnParent.querySelectorAll(tabBtn);
				btns.forEach(function (tabBtn) {
					tabBtn.classList.remove("active");
					var hideTarget = tabBtn.getAttribute("data-target");
					if (parent.querySelector(hideTarget)) {
						parent.querySelector(hideTarget).style.display = "none";
					}
				});
				el.target.classList.add("active");
				var showTarget = el.target.getAttribute("data-target");
				if (parent.querySelector(showTarget)) {
					parent.querySelector(showTarget).style.display = "block";
				}
			}
		});
	}
	function commentForm(element = null) {
		var commentFormButtons = element ? element.querySelectorAll(".dr-form-tab-btn") : document.querySelectorAll(".dr-form-tab-btn");
		commentFormButtons.forEach(function (tabBtn) {
			if (!tabBtn.matches(".active")) {
				tabBtn
					.closest(".dr-comment-form")
					.querySelector(tabBtn.dataset.target).style.display =
					"none";
			}
		});
	}
	function dropzone(element = null) {
		var dropzone = element ? element.querySelector(".dropzone") : document.querySelector(".dropzone");
		if (dropzone !== null) {
			if (typeof Dropzone !== 'undefined') {
				if (!dropzone.dropzone) {
					var DZOBJ_review_images = new Dropzone(dropzone, {
						acceptedFiles: "image/jpeg, image/gif, image/png, image/webp, image/avif",
						url: delicious_recipes_pro.ajax_url,
						uploadMultiple: true,
						resizeWidth: 1500,
						resizeMimeType: "image/jpeg",
						resizeMethod: "crop",
						resizeQuality: 65,
						createImageThumbnails: true,
						parallelUploads: 100,
						maxFiles: 20,
						maxFilesize: 5,
						paramName: "gallery",
						dictDefaultMessage: delicious_recipes_pro.upload_review_pic_msg,
					});
					DZOBJ_review_images.on("sending", function (file, xhr, formData) {
						var nonce = document.getElementsByName("review_images_nonce")[0]
							.value;
						var recipe_id = document.getElementsByName("comment_post_ID")[0]
							.value;
						formData.append(
							"action",
							"delicious_recipes_review_images_upload"
						);
						formData.append("nonce", nonce);
						formData.append("recipe_id", recipe_id);
					});

					DZOBJ_review_images.on("success", function (file, response) {
						if (response !== "error") {
							var review_images = JSON.parse(response);
							var existing_images = document.getElementsByName(
								"review_images[]"
							)[0].value;
							let allImagesArray = existing_images
								? review_images?.attachment_ids.concat(
									existing_images && JSON.parse(existing_images)
								)
								: review_images?.attachment_ids;
							dropzone.querySelector(
								"input[name='review_images[]']"
							).value = JSON.stringify([...new Set(allImagesArray)]);
						}
					});
				}
			}
		}
	}
	function relatedRecipes(element = null) {
		// Related Posts
		var relatedposts = element ? element.querySelector(".dr-related-posts-splide") : document.querySelector(".dr-related-posts-splide");
		if (relatedposts !== null) {
			var recipeID = relatedposts.dataset.id;
			var post = element ? element.querySelector(".dr-related-splide-" + recipeID) : document.querySelector(".dr-related-splide-" + recipeID);

			if (post !== null) {
				var splide = new Splide(post, {
					type: "fade",
					perPage: 1,
					pagination: false,
				});

				splide.mount();
			}
		}
	}

	// // Splide slider for frontend recipe equipment
	// function recipeEquipment(element = null) {
	// 	const splides = element ? element.querySelectorAll('.dr-equipment-slider-wrapper') : document.querySelectorAll('.dr-equipment-slider-wrapper');
	// 	const splidesCount = splides[0]?.querySelectorAll('.splide__slide').length;
	// 	let options = {
	// 		gap: '30px',
	// 		pagination: false,
	// 		perPage: 3,
	// 		arrows: splidesCount > 3,
	// 		type: splidesCount > 3 ? 'loop' : 'slide',
	// 		breakpoints: {
	// 			1024: {
	//                 perPage: 2,
	//                 arrows: splidesCount > 2,
	//                 type: splidesCount > 2 ? 'loop' : 'slide', // Conditional loop
	//             },
	//             640: {
	//                 perPage: 1,
	//                 arrows: splidesCount > 1,
	//                 type: splidesCount > 1 ? 'loop' : 'slide', // Conditional loop
	//             }
	// 		},
	// 	};

	// 	splides.forEach(splide => {
	// 		new Splide(splide, options).mount();
	// 	});
	// }

	// Manually handle openeing gallery for purpose of reusing code in autolad recipes.
	function openGallery(element = null) {
		const root = element || document;
		const fslightbox = root.querySelectorAll('[data-fslightbox]');
		const galleryButton = root.querySelector('.view-gallery-btn');
		let gallerySources = [];

		if (!galleryButton) {
			return;
		}

		fslightbox.forEach((item, index) => {
			const instanceName = item.dataset.fslightbox;
			if (instanceName == 'gallery') {
				gallerySources.push(item.href);
			}
		});

		const newInstance = new window.FsLightbox('gallery');
		newInstance.props.sources = gallerySources;
		galleryButton.addEventListener('click', function (e) {
			e.preventDefault();
			newInstance.open();
		});
	}

	updatedReviewForm();
	reviewFormRating();
	ratingWithoutReview();
	if (document.querySelector('.dropzone')) {
		dropzone();
	}
	relatedRecipes();
	// recipeEquipment();
	openGallery();

	function forFslightbox(element = null) {
		const root = element || document;
		const fslightbox = root.querySelectorAll('[data-fslightbox]');
		fslightbox.forEach((item, index) => {
			const instanceName = item.dataset.fslightbox; // Give your instance a unique name
			const newInstance = new window.FsLightbox(instanceName);
			item.addEventListener('click', function (e) {
				e.preventDefault();
				newInstance.props.sources = [item.href];
				newInstance.open();
			});
		});
	}

	if (delicious_recipes_pro.enable_autoload) {
		let autoloadSelector =
			delicious_recipes_pro.autoload_filter === "prev"
				? ".nav-previous .next-recipe"
				: ".nav-next .next-recipe";
		let nextRecipe = document.querySelectorAll(autoloadSelector);
		if (nextRecipe.length > 0) {
			let nextRecipeLinks = [];
			for (let i = 0; i < nextRecipe.length; i++) {
				nextRecipeLinks.push(nextRecipe[i].href);
			}

			function getPath() {
				var path = nextRecipeLinks[this.loadCount];
				return path;
			}
			let image = document.querySelector(
				".dr-post-summary .dr-image img"
			);
			let wishlist = document.querySelector(
				".dr-floating-box .dr-add-to-wishlist-single .dr-recipe-wishlist"
			);
			let likes = document.querySelector(".dr-floating-box .post-like");
			let floatingBarData = [
				{
					path: window.location.href,
					id: document.querySelector(".dr-single-recipe").dataset.id,
					title: document.querySelector("title").innerText,
					image: image ? image.src : "",
					wishlist: wishlist ? wishlist.innerHTML : "",
					likes: likes ? likes.innerHTML : "",
				},
			];

			let elem = document.querySelector(
				delicious_recipes_pro.autoload_selector
			);
			let infScroll = new InfiniteScroll(elem, {
				// options
				path: getPath,
				append: delicious_recipes_pro.autoload_append,
				checkLastPage: false,
			});

			infScroll.on("load", onPageLoad);
			function onPageLoad(body, path) {
				if (
					infScroll.loadCount ==
					delicious_recipes_pro.autoload_perpage - 1
				) {
					infScroll.options.loadOnScroll = false;
					// remove event listener
					relatedRecipes(body);
					ratingWithoutReview(body)
					dropzone(body);
					commentForm(body);
					drCustomTab(body, ".dr-comment-list-btn");
					// recipeEquipment(body);
					updatedReviewForm(body);
					window.createRatingSystem(body, '.wpd-rating-container');
					forFslightbox(body);
					openGallery(body);
					reviewFormRating(body);

					// init light gallery
					infScroll.off(onPageLoad);
				} else {
					// add more url to nextRecipeLinks
					ratingWithoutReview(body)
					dropzone(body);
					commentForm(body);
					drCustomTab(body, ".dr-comment-list-btn");
					relatedRecipes(body);
					// recipeEquipment(body);
					updatedReviewForm(body);
					window.createRatingSystem(body, '.wpd-rating-container');
					forFslightbox(body);
					openGallery(body);
					reviewFormRating(body);

					let recipeID = body.querySelector(".dr-single-recipe")
						.dataset.id;
					let image = body.querySelector(
						".dr-post-summary .dr-image img"
					);
					let wishlist = body.querySelector(
						".dr-floating-box .dr-add-to-wishlist-single .dr-recipe-wishlist"
					);
					let likes = body.querySelector(
						".dr-floating-box .post-like"
					);
					let templateData = {
						path: path,
						id: recipeID,
						title: body.querySelector(".dr-entry-title").innerText,
						image: image ? image.src : "",
						wishlist: wishlist ? wishlist.innerHTML : "",
						likes: likes ? likes.innerHTML : "",
					};
					floatingBarData.push(templateData);

					var nextRecipe = body.querySelectorAll(autoloadSelector);
					for (let i = 0; i < nextRecipe.length; i++) {
						nextRecipeLinks.push(nextRecipe[i].href);
					}
				}
			}

			infScroll.on("history", function (title, path) {
				let pageTitle = document.querySelector("title");
				pageTitle.innerText = title;

				// reset timer if active
				let timer = document.getElementById("dr-recipe-timer");
				if (timer) {
					reset_clock();
				}

				// add wp.template to floating bar
				let floatingBar = document.querySelector(
					".dr-floating-bar-wrapper"
				);
				if (floatingBar) {
					let data = floatingBarData.filter(
						(item) => item.path === path
					);
					if (data[0]) {
						let template = wp.template("floating-bar-tmp");
						jQuery(".dr-floating-bar-wrapper").html(
							template(data[0])
						);
					}
				}
			});
			window["recipeProGlobal"] = floatingBarData;
		}
	}

	if (delicious_recipes_pro.enable_reaction) {
		function fetchReactions() {
			var $reactElement = jQuery('[data-reaction_uid]');

			if (!$reactElement.length) {
				return;
			}

			var recipeIds = [];
			$reactElement.each(function (index, element) {
				recipeIds = [...recipeIds, jQuery(element).data('reaction_uid')];
			});

			recipeIds = [...new Set(recipeIds.filter(element => !!element))];

			if (!recipeIds.length) {
				return;
			}

			jQuery.ajax({
				url: delicious_recipes_pro.ajax_url,
				type: 'POST',
				data: {
					action: 'delicious_recipes_pro_fetch_reactions',
					ids: [...recipeIds]
				},
				success: function (response) {
					if (true !== response.success) {
						$reactElement.removeClass('loading');

						return;
					}

					if (response.data?.recipes && 'object' === typeof response.data.recipes) {
						for (var recipe_id in response.data.recipes) {
							var recipe = response.data.recipes[recipe_id];
							if (recipe?.yummy) {
								jQuery(`[data-reaction_uid="${recipe_id}"][data-reaction="yummy"] .dr-reaction-count`).text(recipe.yummy.length);
							}

							if (recipe?.love) {
								jQuery(`[data-reaction_uid="${recipe_id}"][data-reaction="love"] .dr-reaction-count`).text(recipe.love.length);
							}

							if (recipe?.wow) {
								jQuery(`[data-reaction_uid="${recipe_id}"][data-reaction="wow"] .dr-reaction-count`).text(recipe.wow.length);
							}

							if (recipe?.happy) {
								jQuery(`[data-reaction_uid="${recipe_id}"][data-reaction="happy"] .dr-reaction-count`).text(recipe.happy.length);
							}

							if (recipe?.sad) {
								jQuery(`[data-reaction_uid="${recipe_id}"][data-reaction="sad"] .dr-reaction-count`).text(recipe.sad.length);
							}

							$reactElement.removeClass('loading');
						}
					}
				},
				error: function () {
					$reactElement.removeClass('loading');
				}
			})
		};

		fetchReactions();

		delicious_recipes.utilities.on("click", ".dr-reaction-section .dr-reaction", function () {
			if (this.dataset.disabled == "true") {
				return;
			}
			this.dataset.disabled = "true";

			let unique_user_id = "";
			if ( document.cookie.includes("delicious_recipes_user_identifier_for_emoji_reaction") ) {
				unique_user_id = document.cookie.replace(/(?:(?:^|.*;\s*)delicious_recipes_user_identifier_for_emoji_reaction\s*\=\s*([^;]*).*$)|^.*$/, "$1");
			} else {
				unique_user_id = Math.random().toString(36).substring(2, 15);
				document.cookie = "delicious_recipes_user_identifier_for_emoji_reaction=" + unique_user_id + "; path=/";
			}

			let current = this;
			let reaction_id = current.dataset.reaction;
			let reaction_uid = current.dataset.reaction_uid;
			let push = 1;
			current.classList.add('loading');
			let reactionCount = current.querySelector('.dr-reaction-count');
			let total = parseInt(reactionCount.innerHTML);
			if (current.classList.contains('active')) {
				total--;
				push = '-1';
			} else {
				total++;
			}
			let nonce = document.querySelector('input[name="delicious_recipes_reaction_nonce"]').value;

			// ajax
			let data = {
				action: 'delicious_recipes_pro_add_reaction',
				reaction_id: reaction_id,
				reaction_uid: reaction_uid,
				push: push,
				nonce: nonce,
				unique_user_id: unique_user_id
			};

			jQuery.post(delicious_recipes_pro.ajax_url, data, function (response) {
				if (response.success) {
					if (response.data.unique) {
						let previousReactions = document.querySelectorAll('.dr-reaction-section #dr-reaction-' + reaction_uid + ' .dr-reaction.active');
						for (let i = 0; i < previousReactions.length; i++) {
							if (previousReactions && !previousReactions[i].matches('[data-reaction="' + current.dataset.reaction + '"]')) {
								previousReactions[i].classList.remove('active');
							}
							let previousReactionCount = previousReactions[i].querySelector('.dr-reaction-count');
							let _total = parseInt(previousReactionCount.innerHTML);
							_total--;
							previousReactionCount.innerHTML = _total < 0 ? 0 : _total;
						}
					}
					let _total = response.data.total || total
					reactionCount.innerHTML = _total < 0 ? 0 : _total;
					current.classList.toggle('active', !current.classList.contains('active'));
				}
				current.classList.remove('loading');
				current.dataset.disabled = "false";
			});
		});
	}

	// modal
	const drModal = (btn) => {
		let targetModal = document.querySelector(btn.dataset.modal);
		let closeBtn = targetModal.querySelector(".custom-modal-close");

		function modalStyle(show) {
			return function () {
				targetModal.classList.toggle("show", show);
			};
		}
		btn.onclick = modalStyle(true);
		closeBtn.onclick = modalStyle(false);
		window.onclick = function (e) {
			if (e.target.id == targetModal.id) {
				targetModal.classList.remove("show");
			}
		};
	};

	let modalBtns = document.querySelectorAll("[data-modal]");
	modalBtns.forEach((btn) => {
		drModal(btn);
	});

	// dashboard portal
	dashboardPortal();
}

window.addEventListener("load", recipeProScripts);