// Check authentication
requireAuth();

// Initialize
document.addEventListener("DOMContentLoaded", () => {
	loadUserProfile();
	loadServices();
});

// Show loading state
function showLoadingState() {
	const container = document.getElementById("servicesList");
	container.innerHTML = `
		<div class="loading-container" style="text-align: center; padding: 3rem;">
			<div class="spinner"></div>
			<p style="margin-top: 1rem; color: var(--text-secondary);">Loading services...</p>
		</div>
	`;
}

// Show error state
function showErrorState(message) {
	const container = document.getElementById("servicesList");
	container.innerHTML = `
		<div style="text-align: center; padding: 3rem;">
			<div style="font-size: 3rem; margin-bottom: 1rem;">⚠️</div>
			<p style="color: var(--error-red); margin-bottom: 1rem; font-weight: 500;">${message}</p>
			<button class="btn btn-primary" onclick="loadServices()">Retry</button>
		</div>
	`;
}

// Show empty state
function showEmptyState() {
	const container = document.getElementById("servicesList");
	container.innerHTML = `
		<div style="text-align: center; padding: 3rem;">
			<div style="font-size: 3rem; margin-bottom: 1rem;">📅</div>
			<p style="color: var(--text-secondary); font-size: 1.125rem; font-weight: 500;">No services available</p>
			<p style="color: var(--text-tertiary); font-size: 0.875rem; margin-top: 0.5rem;">Check back later for upcoming services</p>
		</div>
	`;
}

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

		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;

		const departmentEl = document.getElementById("profileCampus");
		if (user.department_name) {
			departmentEl.textContent = user.department_name;
		} else {
			departmentEl.textContent = "--";
		}

		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 services
async function loadServices() {
	showLoadingState();

	try {
		const response = await apiRequest(API_ENDPOINTS.SERVICES_LIST);
		const services = response.data.services;

		displayServices(services);
	} catch (error) {
		console.error("Failed to load services:", error);
		showErrorState("Failed to load services");
	}
}

// Display services
function displayServices(services) {
	const listContainer = document.getElementById("servicesList");

	if (services.length === 0) {
		showEmptyState();
		return;
	}

	listContainer.innerHTML = "";

	services.forEach((service) => {
		const card = document.createElement("div");
		card.className = "service-card";

		const startDate = new Date(service.start_time);
		const endDate = new Date(service.end_time);

		const dateStr = startDate.toLocaleDateString("en-US", {
			weekday: "short",
			month: "short",
			day: "numeric",
			year: "numeric",
		});

		const startTime = startDate.toLocaleTimeString("en-US", {
			hour: "2-digit",
			minute: "2-digit",
		});

		const endTime = endDate.toLocaleTimeString("en-US", {
			hour: "2-digit",
			minute: "2-digit",
		});

		const now = new Date();
		const isActive = now >= startDate && now <= endDate;
		const isPast = now > endDate;
		const isFuture = now < startDate;

		let statusBadge = "";
		if (isActive) {
			statusBadge =
				'<span class="status-badge status-active">Active Now</span>';
		} else if (isPast) {
			statusBadge = '<span class="status-badge status-past">Completed</span>';
		} else if (isFuture) {
			statusBadge = '<span class="status-badge status-future">Upcoming</span>';
		}

		card.innerHTML = `
            <div class="service-card-header">
                <div class="service-name-text">${service.name}</div>
                ${statusBadge}
            </div>
            <div class="service-card-body">
                <!--${
									service.description
										? `<p class="service-description">${service.description}</p>`
										: ""
								}-->
                <div class="service-detail">
                    <span class="detail-icon">📅</span>
                    <span class="detail-text">${dateStr}</span>
                </div>
                <div class="service-detail">
                    <span class="detail-icon">🕐</span>
                    <span class="detail-text">${startTime} - ${endTime}</span>
                </div>
                ${
									service.location
										? `<div class="service-detail"><span class="detail-icon">📍</span><span class="detail-text">${service.location}</span></div>`
										: ""
								}
                ${
									service.is_reward_based
										? `<div class="service-detail"><span class="detail-icon">🎁</span><span class="detail-text">Reward-based: Attend ${service.attendance_required} times to earn a reward</span></div>`
										: ""
								}
            </div>
        `;

		listContainer.appendChild(card);
	});
}

// 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";
	}
}
