document.addEventListener("DOMContentLoaded", function() {
	// Admin Gallery Swiper
	if (typeof Swiper !== "undefined") {
		const adminGallerySwiper = new Swiper('.athena-admin-gallery', {
			loop: true,
			slidesPerView: 1,
			spaceBetween: 20,
			speed: 1300,
			autoplay: {
				delay: 2000,
				disableOnInteraction: false,
				pauseOnMouseEnter: true,
			},
			pagination: {
				el: ".swiper-pagination",
				clickable: true,
			},
		});
	}
	// END Admin Gallery Swiper

	// Athena Accordion
	document.addEventListener('click', function(e) {
		const athenaAccordionTitle = e.target.closest(".athena-wp-admin .athena-accordion .athena-accordion-title");
		if (!athenaAccordionTitle) return;

		const athenaAccordionItem = athenaAccordionTitle.closest(".athena-accordion-item");
		const athenaAccordionContent = athenaAccordionItem.querySelector(".athena-wp-admin .athena-accordion .athena-accordion-content");
		const athenaAccordionItemIsOpen = athenaAccordionItem.classList.contains('active');

		document.querySelectorAll(".athena-wp-admin .athena-accordion .athena-accordion-item.active").forEach(openAccordionItem => {
			if (openAccordionItem !== athenaAccordionItem) {
				openAccordionItem.classList.remove("active");
				const openContent = openAccordionItem.querySelector(".athena-wp-admin .athena-accordion .athena-accordion-content");
				openContent.style.height = openContent.scrollHeight + 'px';
				requestAnimationFrame(() => {
					openContent.style.height = '0';
				});
			}
		});

		if (!athenaAccordionItemIsOpen) {
			athenaAccordionItem.classList.add('active');
			athenaAccordionContent.style.height = athenaAccordionContent.scrollHeight + 'px';
		} else {
			athenaAccordionContent.style.height = athenaAccordionContent.scrollHeight + 'px';
			requestAnimationFrame(() => {
				athenaAccordionContent.style.height = '0';
			});
			athenaAccordionItem.classList.remove('active');
		}
	});
	// END Athena Accordion

	// Full Reindex
	const fullReindexForm = document.getElementById('athena-full-reindex-form');
	if (fullReindexForm) {
		const reindexButton = document.getElementById('athena-full-reindex-btn');
		const reindexInProgressMessage = document.getElementById('athena-reindex-in-progress-msg');
		const reindexResponseMessage = document.querySelector('.athena-wp-admin .athena-reindex-response');
		const reindexResponseMessageParagraph = reindexResponseMessage.querySelector('p');

		// Progress UI elements
		const progressBarWrapper = document.querySelector('.athena-reindex-progress-bar');
		const progressBarFill = document.getElementById('athena-progress-bar-fill');
		const progressText = document.getElementById('athena-progress-text');
		const showLogsBtn = document.getElementById('athena-show-logs-btn');
		const logModal = document.getElementById('athena-log-modal');
		const closeModalBtn = document.querySelector('.athena-close-modal');
		const logViewerContent = document.getElementById('athena-log-viewer-content');

		if (!reindexButton || !reindexInProgressMessage) return;

		// Modal Interactions
		if (showLogsBtn && logModal && closeModalBtn) {
			showLogsBtn.addEventListener('click', () => {
				logModal.classList.remove('hidden');
				// Automatically fetch logs when opening if not currently polling
				if (!reindexCheckInterval && !isStartingReindex) {
					fetchLogsOnce();
				}
			});

			closeModalBtn.addEventListener('click', () => {
				logModal.classList.add('hidden');
			});

			// Click outside modal to close
			window.addEventListener('click', (e) => {
				if (e.target === logModal) {
					logModal.classList.add('hidden');
				}
			});
		}

		function updateLogViewer(logLines) {
			if (logViewerContent && logLines && logLines.length > 0) {
				const isScrolledToBottom = logViewerContent.scrollHeight - logViewerContent.clientHeight <= logViewerContent.scrollTop + 10;
				// Append new lines (offset approach - we only receive new lines from server)
				logViewerContent.textContent += logLines.join('\n') + '\n';

				// Auto-scroll to bottom if they were already at the bottom
				if (isScrolledToBottom) {
					logViewerContent.scrollTop = logViewerContent.scrollHeight;
				}
			}
		}

		function fetchLogsOnce() {
			fetch(ajaxurl + '?action=athena_check_reindex_status&last_line_count=' + lastLineCount, { method: 'GET' })
				.then((res) => res.json())
				.then((data) => {
					if (data.log_lines) {
						updateLogViewer(data.log_lines);
					}
					if (data.total_lines !== undefined) {
						lastLineCount = data.total_lines;
					}
				});
		}
		// END Modal Interactions

		let reindexCheckInterval = null;
		let lastLineCount = 0;
		let isStartingReindex = false;

		function startReindexStatusCheck() {
			// If there is already an active interval, do not start a new one
			if (reindexCheckInterval) return;

			reindexCheckInterval = setInterval(() => {
				fetch(ajaxurl + '?action=athena_check_reindex_status&last_line_count=' + lastLineCount, { method: 'GET' })
					.then((res) => res.json())
					.then((data) => {
						// Update progress UI
						if (progressBarFill && progressText) {
							const percentage = data.progress_percentage || 0;
							progressBarFill.style.width = percentage + '%';
							progressText.textContent = percentage + '% Complete';
						}

						// Update logs
						if (data.log_lines) {
							updateLogViewer(data.log_lines);
						}

						// Track how many lines we have for next poll
						if (data.total_lines !== undefined) {
							lastLineCount = data.total_lines;
						}

						if (!data.in_progress) {
							clearInterval(reindexCheckInterval);
							reindexCheckInterval = null;
							reindexButton.disabled = false;
							reindexInProgressMessage.style.display = 'none';
							if (progressBarWrapper) progressBarWrapper.style.display = 'none';

							if (data.is_reindex_successful && data.is_reindex_successful === 'success') {
								reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
								reindexResponseMessage.classList.add('success-message');
								reindexResponseMessageParagraph.textContent = "The reindex was successfully completed!";
							} else {
								reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
								reindexResponseMessage.classList.add('warning-message');
								reindexResponseMessageParagraph.textContent = "Something went wrong. Please try again!";
							}
						}
					})
					.catch(() => {
						// In case of error, terminate the loop
						clearInterval(reindexCheckInterval);
						reindexCheckInterval = null;
						reindexButton.disabled = false;
						reindexInProgressMessage.style.display = 'none';
						if (progressBarWrapper) progressBarWrapper.style.display = 'none';

						reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
						reindexResponseMessage.classList.add('warning-message');
						reindexResponseMessageParagraph.textContent = "Something went wrong. Please try again!";

					});
			}, 2000);
		}

		// If the reindex is already active (and the user, for example, refreshed or opened another page)
		if (reindexInProgressMessage.style.display === 'block') {
			startReindexStatusCheck();
		}

		fullReindexForm.addEventListener('submit', function(e) {
			e.preventDefault();

			reindexButton.disabled = true;
			reindexInProgressMessage.style.display = 'block';
			if (progressBarWrapper) progressBarWrapper.style.display = 'block';
			isStartingReindex = true;

			// Reset progress bar visually on start
			if (progressBarFill && progressText) {
				progressBarFill.style.width = '0%';
				progressText.textContent = '0% Complete';
			}

			// Reset log offset counter and clear viewer
			lastLineCount = 0;
			if (logViewerContent) {
				logViewerContent.textContent = '';
			}

			reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
			reindexResponseMessage.classList.add('hidden');
			reindexResponseMessageParagraph.textContent = '';

			fetch(ajaxurl, {
				method: 'POST',
				body: new URLSearchParams({
					action: 'athena_full_reindex_action',
					athena_full_reindex_nonce: fullReindexForm.querySelector('[name="athena_full_reindex_nonce"]').value
				})
			})
				.then(res => res.json())
				.then(data => {
					isStartingReindex = false;
					if (data.success) {
						startReindexStatusCheck();
					} else {
						reindexButton.disabled = false;
						reindexInProgressMessage.style.display = 'none';
						if (progressBarWrapper) progressBarWrapper.style.display = 'none';
						reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
						reindexResponseMessage.classList.add('warning-message');
						reindexResponseMessageParagraph.textContent = data.data || 'Failed to start reindex.';
					}
				})
				.catch(() => {
					isStartingReindex = false;
					reindexButton.disabled = false;
					reindexInProgressMessage.style.display = 'none';
					if (progressBarWrapper) progressBarWrapper.style.display = 'none';
					reindexResponseMessage.classList.remove('hidden', 'warning-message', 'success-message');
					reindexResponseMessage.classList.add('warning-message');
					reindexResponseMessageParagraph.textContent = 'Network error. Please try again.';
				});
		});

		// Stop Reindex Logic
		const stopReindexBtn = document.getElementById('athena-stop-reindex-btn');
		if (stopReindexBtn) {
			stopReindexBtn.addEventListener('click', function (e) {
				e.preventDefault();

				if (!confirm('Are you sure you want to stop the reindexer?')) {
					return;
				}

				stopReindexBtn.style.pointerEvents = 'none';
				stopReindexBtn.textContent = 'Stopping...';

				fetch(ajaxurl, {
					method: 'POST',
					body: new URLSearchParams({
						action: 'athena_stop_reindex_action',
						athena_stop_reindex_nonce: fullReindexForm.querySelector('[name="athena_full_reindex_nonce"]').value
					})
				})
				.then(res => res.json())
				.then(data => {
					if (data.success) {
						clearInterval(reindexCheckInterval);
						reindexCheckInterval = null;

						reindexButton.disabled = false;
						reindexInProgressMessage.style.display = 'none';
						if (progressBarWrapper) progressBarWrapper.style.display = 'none';

						reindexResponseMessage.classList.remove('hidden', 'success-message');
						reindexResponseMessage.classList.add('warning-message');
						reindexResponseMessageParagraph.textContent = 'Reindex was stopped manually.';

						stopReindexBtn.style.pointerEvents = 'auto';
						stopReindexBtn.textContent = 'Stop Reindex';
					} else {
						stopReindexBtn.style.pointerEvents = 'auto';
						stopReindexBtn.textContent = 'Stop Reindex';
						alert(data.data || 'Failed to stop reindex.');
					}
				})
				.catch(() => {
					stopReindexBtn.style.pointerEvents = 'auto';
					stopReindexBtn.textContent = 'Stop Reindex';
					alert('Network error while trying to stop reindex.');
				});
			});
		}
		// END Stop Reindex Logic
	}
	// END Full Reindex

	// Configuration Form
	const configurationForm = document.getElementById('athena-configuration-form');
	if (configurationForm) {
		const configurationFormSubmitButton = configurationForm.querySelector('input[type="submit"]');
		configurationFormSubmitButton.disabled = true;

		const configurationFormResponse = document.querySelector('#athena-configuration-form .athena-form-response');
		const configurationFormResponseParagraph = document.querySelector('#athena-configuration-form .athena-form-response p');

		// Success message when reloading the page and saving configuration data
		if (sessionStorage.getItem('settings_saved_success') && configurationFormResponse) {
			configurationFormResponse.classList.remove('hidden');
			configurationFormResponse.classList.add('success-message');
			configurationFormResponseParagraph.textContent = 'Settings saved successfully!';

			sessionStorage.removeItem('settings_saved_success');
			setTimeout(() => {
				configurationFormResponse.classList.add('hidden');
				configurationFormResponse.classList.remove('success-message');
				configurationFormResponseParagraph.textContent = '';
			}, 45000);
		}

		configurationForm.querySelectorAll('input, select, textarea').forEach(el => {
			el.dataset.savedValue = el.value;

			el.addEventListener('input', () => {
				const isChanged = Array.from(configurationForm.querySelectorAll('input, select, textarea'))
					.some(input => input.value !== input.dataset.savedValue);

				configurationFormSubmitButton.disabled = !isChanged;

				if (el.checkValidity()) {
					el.classList.remove('form-warning');
				}
			});
		});

		configurationForm.addEventListener('submit', function(e) {
			e.preventDefault();

			const configurationFormData = new FormData(configurationForm);

			// Reset Response Messages
			configurationFormResponse.classList.remove('warning-message', 'success-message');
			configurationFormResponseParagraph.textContent = '';
			configurationFormResponse.classList.add('hidden');
			configurationForm.querySelectorAll('input, textarea, select').forEach(el => el.classList.remove('form-warning'));
			// END Reset Response Messages

			// Front-end validation
			let dataIsValid = true;
			configurationForm.querySelectorAll('[required]').forEach(el => {
				if (!el.checkValidity()) {
					el.classList.add('form-warning');
					dataIsValid = false;
				}
			});

			if (!dataIsValid) {
				configurationFormResponse.classList.add('warning-message');
				configurationFormResponse.classList.remove('hidden');
				configurationFormResponseParagraph.textContent = 'Please fill in all required fields.';
				return;
			}
			// END Front-end validation

			// Send data via AJAX
			configurationFormData.append('action', 'athena_configuration_form');
			configurationFormSubmitButton.disabled = true;

			fetch(ajaxurl, {
				method: 'POST',
				body: configurationFormData
			})
				.then(res => res.json())
				.then(data => {
					if (data.success) {
						sessionStorage.setItem('settings_saved_success', '1');
						location.reload();
					} else {
						configurationFormResponse.classList.remove('hidden');
						configurationFormResponse.classList.add('warning-message');
						configurationFormResponseParagraph.textContent = data.data || 'Something went wrong. Please try again.';
					}
				})
				.catch(err => {
					configurationFormResponse.classList.remove('hidden');
					configurationFormResponse.classList.add('warning-message');
					configurationFormResponseParagraph.textContent = 'Failed to send settings. Please try again later.';
				});
			// END Send data via AJAX
		});

		configurationForm.querySelectorAll('.athena-form-field-wrp').forEach(wrapper => {
			const input = wrapper.querySelector('input, textarea');
			const clearBtn = wrapper.querySelector('.clear-field');

			input.addEventListener('input', () => {
				clearBtn.style.display = input.value ? 'block' : 'none';
			});

			clearBtn.addEventListener('click', () => {
				input.value = '';
				clearBtn.style.display = 'none';
				input.dispatchEvent(new Event('input'));
				input.focus();
			});
		});
	}
	// END Configuration Form

	// Contact Form
	const contactUsForm = document.getElementById('athena-contact-us-form');
	if (contactUsForm) {
		contactUsForm.querySelectorAll('[required]').forEach(el => {
			el.addEventListener('input', function() {
				if (el.checkValidity()) {
					el.classList.remove('form-warning');
				}
			});
		});

		contactUsForm.addEventListener('submit', function(e) {
			e.preventDefault();

			const contactUsFormData = new FormData(contactUsForm);
			const contactUsFormResponse = document.querySelector('#athena-contact-us-form .athena-form-response');
			const contactUsFormResponseParagraph = document.querySelector('#athena-contact-us-form .athena-form-response p');
			const submitButton = contactUsForm.querySelector('input[type="submit"]');

			// Reset Response Messages
			contactUsFormResponse.classList.remove('warning-message', 'success-message');
			contactUsFormResponseParagraph.textContent = '';
			contactUsFormResponse.classList.add('hidden');
			contactUsForm.querySelectorAll('input, textarea, select').forEach(el => el.classList.remove('form-warning'));
			// END Reset Response Messages

			// Front-end validation
			let dataIsValid = true;
			contactUsForm.querySelectorAll('[required]').forEach(el => {
				if (!el.checkValidity()) {
					el.classList.add('form-warning');
					dataIsValid = false;
				}
			});

			if (!dataIsValid) {
				contactUsFormResponse.classList.add('warning-message');
				contactUsFormResponse.classList.remove('hidden');
				contactUsFormResponseParagraph.textContent = 'Please fill in all required fields.';
				return;
			}
			// END Front-end validation

			// Send data via AJAX
			contactUsFormData.append('action', 'athena_send_contact_email');
			submitButton.disabled = true;

			fetch(ajaxurl, {
				method: 'POST',
				body: contactUsFormData
			})
				.then(res => res.json())
				.then(data => {
					contactUsFormResponse.classList.remove('hidden');
					if (data.success) {
						contactUsFormResponse.classList.add('success-message');
						contactUsFormResponseParagraph.textContent = 'Your message has been sent successfully!';
						contactUsForm.reset();

						setTimeout(() => {
							contactUsFormResponse.classList.add('hidden');
							contactUsFormResponse.classList.remove('success-message');
							contactUsFormResponseParagraph.textContent = '';
						}, 45000);
					} else {
						contactUsFormResponse.classList.add('warning-message');
						contactUsFormResponseParagraph.textContent = data.data || 'Something went wrong. Please try again.';
					}
				})
				.catch(err => {
					contactUsFormResponse.classList.remove('hidden');
					contactUsFormResponse.classList.add('warning-message');
					contactUsFormResponseParagraph.textContent = 'Failed to send message. Please try again later.';
				})
				.finally(() => submitButton.disabled = false);
			// END Send data via AJAX
		});
	}
	// END Contact Form
});