if (getAuthToken()) {
	const user = getUserData();
	if (user.role === "admin") {
		window.location.href = "index.html";
	}
}

document
	.getElementById("adminLoginForm")
	.addEventListener("submit", async (e) => {
		e.preventDefault();

		const email = document.getElementById("email").value;
		const password = document.getElementById("password").value;
		const loginBtn = document.getElementById("loginBtn");
		const errorMessage = document.getElementById("errorMessage");

		// Show loading state
		loginBtn.disabled = true;
		loginBtn.querySelector("span").style.display = "none";
		loginBtn.querySelector(".spinner").style.display = "block";
		errorMessage.style.display = "none";

		try {
			const response = await fetch(`${API_ENDPOINTS.LOGIN}`, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({ email, password }),
			});

			const result = await response.json();

			if (result.success) {
				const role = result.data.user.role;
				const isAuthorized = role === "admin" || role === "superadmin";

				console.log("User role:", role);

				if (!isAuthorized) {
					errorMessage.textContent =
						"Access denied. Admin privileges required.";
					errorMessage.style.display = "block";
					loginBtn.disabled = false;
					loginBtn.querySelector("span").style.display = "block";
					loginBtn.querySelector(".spinner").style.display = "none";
					return;
				}

				localStorage.setItem(STORAGE_KEYS.TOKEN, result.data.token);
				localStorage.setItem(
					STORAGE_KEYS.USER,
					JSON.stringify(result.data.user)
				);

				// Redirect to dashboard
				window.location.href = ADMIN_APP_URLS.DASHBOARD;
			} else {
				errorMessage.textContent =
					result.message || "Login failed. Please try again.";
				errorMessage.style.display = "block";
			}
		} catch (error) {
			console.error("Login error:", error);
			errorMessage.textContent = "An error occurred. Please try again.";
			errorMessage.style.display = "block";
		} finally {
			loginBtn.disabled = false;
			loginBtn.querySelector("span").style.display = "block";
			loginBtn.querySelector(".spinner").style.display = "none";
		}
	});

function togglePassword() {
	const passwordInput = document.getElementById("password");
	passwordInput.type = passwordInput.type === "password" ? "text" : "password";
}
