// Check authentication on page load
requireAuth();

// State
let currentService = null;
let attendanceStatus = null;
let statusInterval = null;

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	updateDateTime();
	setInterval(updateDateTime, 1000);
	loadUserProfile();
	loadActiveService();
	loadAttendanceStatus();

	// Auto-refresh attendance status every 30 seconds
	statusInterval = setInterval(loadAttendanceStatus, 30000);
});

// Clean up on page unload
window.addEventListener("beforeunload", () => {
	if (statusInterval) {
		clearInterval(statusInterval);
	}
});

// Function to refresh the page when the page remains inactive for 5 minutes
let inactivityTimeout;

function resetInactivityTimer() {
	if (inactivityTimeout) {
		clearTimeout(inactivityTimeout);
	}
	inactivityTimeout = setTimeout(() => {
		location.reload();
	}, 5 * 60 * 1000); // 5 minutes
}
// Reset the inactivity timer on user interaction
["mousemove", "keydown", "click", "scroll", "touchstart"].forEach((event) => {
	window.addEventListener(event, resetInactivityTimer);
});

// Initialize the inactivity timer
resetInactivityTimer();

// Update date and time
function updateDateTime() {
	const now = new Date();

	// Update time
	const timeString = now.toLocaleTimeString("en-US", {
		hour: "2-digit",
		minute: "2-digit",
		hour12: true,
	});
	document.getElementById("currentTime").textContent = timeString;

	// Update date
	const dateString = now.toLocaleDateString("en-US", {
		weekday: "long",
		month: "short",
		day: "numeric",
		year: "numeric",
	});
	document.getElementById("currentDate").textContent = dateString;
}

// Load user profile
async function loadUserProfile() {
	try {
		const response = await apiRequest(API_ENDPOINTS.PROFILE);
		const user = response.data.user;

		setUserData(user);

		// Update UI
		const initials = getUserInitials(user.first_name, user.last_name);
		document.getElementById("userAvatar").textContent = initials;
		document.getElementById("profileAvatarLarge").textContent = initials;
		document.getElementById(
			"profileName"
		).textContent = `${user.first_name} ${user.last_name}`;
		document.getElementById("profileEmail").textContent = user.email;

		// Update department/campus
		const departmentEl = document.getElementById("profileDepartment");
		if (user.department_name) {
			departmentEl.textContent = user.department_name;
		} else {
			departmentEl.textContent = "--";
		}

		// Update badges based on role
		const badgesContainer = document.getElementById("profileBadges");
		badgesContainer.innerHTML = "";

		if (user.role_name) {
			const badge = document.createElement("div");
			badge.className = `badge badge-${user.role_name.toLowerCase()}`;
			badge.textContent =
				user.role_name.charAt(0).toUpperCase() + user.role_name.slice(1);
			badgesContainer.appendChild(badge);
		}

		if (user.is_hod) {
			const badge = document.createElement("div");
			badge.className = "badge badge-hod";
			badge.textContent = "HOD";
			badgesContainer.appendChild(badge);
		}
	} catch (error) {
		console.error("Failed to load profile:", error);
	}
}

// Load active service
async function loadActiveService() {
	try {
		const response = await apiRequest(API_ENDPOINTS.ACTIVE_SERVICE);
		if (response.data && response.data.service) {
			currentService = response.data.service;
			document.getElementById("serviceName").textContent = currentService.name;

			// Show location
			if (currentService.location) {
				document.getElementById("serviceLocation").classList.remove("hidden");
				document.getElementById("locationText").textContent =
					currentService.location;
			} else {
				document.getElementById("serviceLocation").classList.add("hidden");
			}
		} else {
			document.getElementById("serviceName").textContent = "No service today";
			document.getElementById("serviceLocation").classList.add("hidden");
			currentService = null;
		}

		updateClockButton();
	} catch (error) {
		console.error("Failed to load active service:", error);
		document.getElementById("serviceName").textContent = "No service today";
		document.getElementById("serviceLocation").classList.add("hidden");
		currentService = null;
		updateClockButton();
	}
}

// Load attendance status
async function loadAttendanceStatus() {
	try {
		const response = await apiRequest(API_ENDPOINTS.ATTENDANCE_STATUS);
		attendanceStatus = response.data;

		updateClockButton();
		updateAttendanceStats();
	} catch (error) {
		console.error("Failed to load attendance status:", error);
		attendanceStatus = null;
		updateClockButton();
	}
}

// Update clock button
function updateClockButton() {
	const button = document.getElementById("clockButton");
	const text = document.getElementById("clockText");

	if (!currentService) {
		button.className = "clock-button inactive";
		text.textContent = "No Service";
		button.disabled = true;
		return;
	}

	if (
		attendanceStatus &&
		attendanceStatus.clocked_in &&
		!attendanceStatus.clocked_out
	) {
		button.className = "clock-button clocked-in";
		text.textContent = "Clock Out";
		button.disabled = false;
	} else if (attendanceStatus && attendanceStatus.clocked_out) {
		button.className = "clock-button inactive";
		text.textContent = "Completed";
		button.disabled = true;
	} else {
		button.className = "clock-button active";
		text.textContent = "Clock In";
		button.disabled = false;
	}
}

// Update attendance stats
function updateAttendanceStats() {
	// Reset stats
	document.getElementById("clockInTime").textContent = "--:--";
	document.getElementById("clockOutTime").textContent = "--:--";
	document.getElementById("timeSpent").textContent = "--";

	if (attendanceStatus && attendanceStatus.clocked_in) {
		if (attendanceStatus.clock_in_time) {
			document.getElementById("clockInTime").textContent = formatTime(
				attendanceStatus.clock_in_time
			);
		}

		if (attendanceStatus.clock_out_time) {
			document.getElementById("clockOutTime").textContent = formatTime(
				attendanceStatus.clock_out_time
			);
		}

		if (attendanceStatus.time_spent_formatted) {
			document.getElementById("timeSpent").textContent =
				attendanceStatus.time_spent_formatted;
		} else if (attendanceStatus.time_spent) {
			document.getElementById("timeSpent").textContent = formatDuration(
				attendanceStatus.time_spent
			);
		}
	}
}

// Handle clock action
async function handleClockAction() {
	if (!currentService) {
		showMessage("No active service available", "error");
		return;
	}

	// Disable button to prevent double-clicks
	const button = document.getElementById("clockButton");
	const originalText = document.getElementById("clockText").textContent;
	button.disabled = true;
	document.getElementById("clockText").textContent = "Processing...";

	// Get user location
	if (!navigator.geolocation) {
		showMessage("Geolocation is not supported by your browser", "error");
		button.disabled = false;
		document.getElementById("clockText").textContent = originalText;
		return;
	}

	navigator.geolocation.getCurrentPosition(
		async (position) => {
			const latitude = position.coords.latitude;
			const longitude = position.coords.longitude;

			try {
				let response;

				if (
					attendanceStatus &&
					attendanceStatus.clocked_in &&
					!attendanceStatus.clocked_out
				) {
					// Clock out
					response = await apiRequest(API_ENDPOINTS.CLOCK_OUT, {
						method: "POST",
						body: JSON.stringify({
							attendance_id: attendanceStatus.id,
							latitude,
							longitude,
						}),
					});

					console.log(response);

					showMessage(
						response.message || "Clocked out successfully",
						"success"
					);

					// Show validity message if applicable
					if (response.data && !response.data.is_valid) {
						setTimeout(() => {
							showMessage(
								"Note: Attendance marked invalid (less than 30 minutes)",
								"error"
							);
						}, 2000);
					}
				} else {
					// Clock in
					response = await apiRequest(API_ENDPOINTS.CLOCK_IN, {
						method: "POST",
						body: JSON.stringify({
							service_occurrence_id: currentService.occurrence_id,
							latitude,
							longitude,
						}),
					});

					showMessage(response.message || "Clocked in successfully", "success");
				}

				// Reload attendance status
				await loadAttendanceStatus();
			} catch (error) {
				showMessage(error.message || "Clock action failed", "error");
				button.disabled = false;
				document.getElementById("clockText").textContent = originalText;
			}
		},
		(error) => {
			let errorMessage =
				"Unable to get your location. Please enable location services.";

			switch (error.code) {
				case error.PERMISSION_DENIED:
					errorMessage =
						"Location permission denied. Please enable location access.";
					break;
				case error.POSITION_UNAVAILABLE:
					errorMessage = "Location information unavailable. Please try again.";
					break;
				case error.TIMEOUT:
					errorMessage = "Location request timed out. Please try again.";
					break;
			}

			showMessage(errorMessage, "error");
			button.disabled = false;
			document.getElementById("clockText").textContent = originalText;
		},
		{
			enableHighAccuracy: true,
			timeout: 10000,
			maximumAge: 0,
		}
	);
}

// Open profile modal
function openProfile() {
	document.getElementById("profileModal").classList.add("active");
}

// Close profile modal
function closeProfile() {
	document.getElementById("profileModal").classList.remove("active");
}

// Handle logout
async function handleLogout() {
	try {
		await apiRequest(API_ENDPOINTS.LOGOUT, {
			method: "POST",
		});
	} catch (error) {
		console.error("Logout error:", error);
	} finally {
		removeAuthToken();
		window.location.href = "login.html";
	}
}
