// ===== Start Login & Register Popup ===== //
document.addEventListener("DOMContentLoaded", function () {
	// Modal elements
	const loginModal = document.getElementById("loginModal");
	const registerModal = document.getElementById("registerModal");

	// Form elements
	const loginForm = document.getElementById("loginForm");
	const registerForm = document.getElementById("registerForm");

	// Error message containers
	const loginError = document.getElementById("loginError");
	const registerError = document.getElementById("registerError");

	// Open modal functions
	window.openLoginModal = function () {
		loginModal.classList.remove("hidden");
		document.body.style.overflow = "hidden";
	};

	window.openRegisterModal = function () {
		registerModal.classList.remove("hidden");
		document.body.style.overflow = "hidden";
	};

	// Close modal functions
	window.closeModal = function (modalId) {
		const modal = document.getElementById(modalId);
		modal.classList.add("hidden");
		document.body.style.overflow = "";

		// Clear form errors
		clearFormErrors(modal);
	};

	// Switch between modals
	window.switchModal = function (fromModal, toModal) {
		closeModal(fromModal);
		setTimeout(() => {
			if (toModal === "loginModal") {
				openLoginModal();
			} else {
				openRegisterModal();
			}
		}, 300);
	};

	// Close modals when clicking outside
	window.onclick = function (event) {
		if (event.target === loginModal) {
			closeModal("loginModal");
		}
		if (event.target === registerModal) {
			closeModal("registerModal");
		}
	};

	// Close modals on escape key
	document.addEventListener("keydown", function (event) {
		if (event.key === "Escape") {
			if (!loginModal.classList.contains("hidden")) {
				closeModal("loginModal");
			}
			if (!registerModal.classList.contains("hidden")) {
				closeModal("registerModal");
			}
		}
	});

	// Clear form errors
	function clearFormErrors(formContainer) {
		const errorMessages = formContainer.querySelectorAll(".error-message");
		errorMessages.forEach((error) => {
			error.textContent = "";
			error.classList.add("hidden");
		});

		const inputs = formContainer.querySelectorAll("input");
		inputs.forEach((input) => {
			input.classList.remove("border-red-500");
		});
	}

	// Display form errors
	function displayFormErrors(formContainer, errors) {
		clearFormErrors(formContainer);

		Object.keys(errors).forEach((field) => {
			const input = formContainer.querySelector(`[name="${field}"]`);
			const errorDiv = formContainer.querySelector(`[data-error="${field}"]`);

			if (input) {
				input.classList.add("border-red-500");
			}
			if (errorDiv) {
				errorDiv.textContent = errors[field];
				errorDiv.classList.remove("hidden");
			}
		});
	}

	// Handle login form submission
	if (loginForm) {
		loginForm.addEventListener("submit", async function (e) {
			e.preventDefault();

			const formData = new FormData(loginForm);
			const submitButton = loginForm.querySelector('button[type="submit"]');
			const originalText = submitButton.textContent;

			// Disable submit button
			submitButton.disabled = true;
			submitButton.textContent = "Signing in...";

			try {
				const response = await fetch(`${BASE_URL}auth/ajax_login`, {
					method: "POST",
					body: formData,
					headers: {
						"X-Requested-With": "XMLHttpRequest",
					},
				});

				const data = await response.json();

				if (data.success) {
					// Login successful
					window.location.reload();
				} else {
					// Display errors
					if (data.errors) {
						displayFormErrors(loginModal, data.errors);
					} else if (data.message) {
						const errorDiv = loginModal.querySelector(".login-error");
						if (errorDiv) {
							errorDiv.textContent = data.message;
							errorDiv.classList.remove("hidden");
						}
					}
				}
			} catch (error) {
				console.error("Error:", error);
				const errorDiv = loginModal.querySelector(".login-error");
				if (errorDiv) {
					errorDiv.textContent = "An error occurred. Please try again.";
					errorDiv.classList.remove("hidden");
				}
			} finally {
				// Re-enable submit button
				submitButton.disabled = false;
				submitButton.textContent = originalText;
			}
		});
	}

	// Handle register form submission
	if (registerForm) {
		registerForm.addEventListener("submit", async function (e) {
			e.preventDefault();

			const formData = new FormData(registerForm);
			const submitButton = registerForm.querySelector('button[type="submit"]');
			const originalText = submitButton.textContent;

			// Disable submit button
			submitButton.disabled = true;
			submitButton.textContent = "Creating account...";

			try {
				const response = await fetch(`${BASE_URL}auth/ajax_register`, {
					method: "POST",
					body: formData,
					headers: {
						"X-Requested-With": "XMLHttpRequest",
					},
				});

				const data = await response.json();

				if (data.success) {
					// Registration successful
					window.location.reload();
				} else {
					// Display errors
					if (data.errors) {
						displayFormErrors(registerModal, data.errors);
					} else if (data.message) {
						const errorDiv = registerModal.querySelector(".register-error");
						if (errorDiv) {
							errorDiv.textContent = data.message;
							errorDiv.classList.remove("hidden");
						}
					}
				}
			} catch (error) {
				console.error("Error:", error);
				const errorDiv = registerModal.querySelector(".register-error");
				if (errorDiv) {
					errorDiv.textContent = "An error occurred. Please try again.";
					errorDiv.classList.remove("hidden");
				}
			} finally {
				// Re-enable submit button
				submitButton.disabled = false;
				submitButton.textContent = originalText;
			}
		});
	}

	// Age verification for register form
	const birthDateInput = document.querySelector('input[name="birth_date"]');
	if (birthDateInput) {
		birthDateInput.addEventListener("change", function () {
			const birthDate = new Date(this.value);
			const today = new Date();
			const age = today.getFullYear() - birthDate.getFullYear();
			const monthDiff = today.getMonth() - birthDate.getMonth();

			if (
				monthDiff < 0 ||
				(monthDiff === 0 && today.getDate() < birthDate.getDate())
			) {
				age--;
			}

			const ageVerification = document.querySelector(
				'input[name="age_verification"]'
			);
			if (age < 18) {
				ageVerification.checked = false;
				alert("You must be 18 years or older to register.");
			}
		});
	}

	// Password confirmation validation
	const passwordConfirm = document.querySelector(
		'input[name="confirm_password"]'
	);
	if (passwordConfirm) {
		passwordConfirm.addEventListener("input", function () {
			const password = document.querySelector('input[name="password"]').value;
			const confirmPassword = this.value;

			if (password !== confirmPassword) {
				this.setCustomValidity("Passwords do not match");
			} else {
				this.setCustomValidity("");
			}
		});
	}
});
// ===== End Login & Register Popup ===== //

// ===== Start home dashboard ===== //
(function () {
	const modal = document.getElementById("video-modal");
	const video = document.getElementById("modal-video");
	const closeBtn = document.getElementById("modal-close");
	const videoCards = document.querySelectorAll(".video-card");

	function openModal(src) {
		video.src = src;
		video.play();
		modal.classList.remove("opacity-0", "pointer-events-none");
		modal.classList.add("opacity-100");
		document.body.style.overflow = "hidden";
	}

	function closeModal() {
		video.pause();
		video.currentTime = 0;
		video.src = "";
		modal.classList.remove("opacity-100");
		modal.classList.add("opacity-0");
		setTimeout(() => {
			modal.classList.add("pointer-events-none");
		}, 500);
		document.body.style.overflow = "";
	}

	videoCards.forEach((card) => {
		card.addEventListener("click", () => {
			const src = card.getAttribute("data-video-src");
			if (src) {
				openModal(src);
			}
		});
	});

	closeBtn.addEventListener("click", closeModal);
	modal.addEventListener("click", (e) => {
		if (e.target === modal) {
			closeModal();
		}
	});

	// Accessibility: close modal on ESC key
	document.addEventListener("keydown", (e) => {
		if (e.key === "Escape" && !modal.classList.contains("opacity-0")) {
			closeModal();
		}
	});
})();

// Modal open/close helpers for login/register modals
function openLoginModal() {
	document.getElementById("loginModal").classList.remove("hidden");
}
function openRegisterModal() {
	document.getElementById("registerModal").classList.remove("hidden");
}
function closeModal(modalId) {
	document.getElementById(modalId).classList.add("hidden");
}
function switchModal(closeId, openId) {
	closeModal(closeId);
	openRegisterModal(openId);
}
// ===== End home dashboard ===== //
