// API Configuration
const API_BASE_URL = "http://localhost/v0-church-attendance-system/api";

// API Endpoints
const API_ENDPOINTS = {
	// Auth
	REGISTER: `${API_BASE_URL}/auth/register`,
	VERIFY: `${API_BASE_URL}/auth/verify`,
	COMPLETE_REGISTRATION: `${API_BASE_URL}/auth/complete-registration`,
	LOGIN: `${API_BASE_URL}/auth/login`,
	LOGOUT: `${API_BASE_URL}/auth/logout`,

	// User
	PROFILE: `${API_BASE_URL}/user/profile`,
	UPDATE_PROFILE: `${API_BASE_URL}/user/update`,

	// Services
	SERVICES_LIST: `${API_BASE_URL}/services/list`,
	ACTIVE_SERVICE: `${API_BASE_URL}/services/active`,

	// Attendance
	CLOCK_IN: `${API_BASE_URL}/attendance/clock-in`,
	CLOCK_OUT: `${API_BASE_URL}/attendance/clock-out`,
	ATTENDANCE_HISTORY: `${API_BASE_URL}/attendance/history`,
	ATTENDANCE_STATUS: `${API_BASE_URL}/attendance/status`,

	// Tickets
	TICKETS_LIST: `${API_BASE_URL}/tickets/list`,
	TICKET_PROGRESS: `${API_BASE_URL}/tickets/progress`,

	REGISTRATION_DATA_LIST: `${API_BASE_URL}/auth/roles`,
};

// Local Storage Keys
const STORAGE_KEYS = {
	TOKEN: "hopepress_token",
	USER: "hopepress_user",
};

// Helper: Get auth token
function getAuthToken() {
	return localStorage.getItem(STORAGE_KEYS.TOKEN);
}

// Helper: Set auth token
function setAuthToken(token) {
	localStorage.setItem(STORAGE_KEYS.TOKEN, token);
}

// Helper: Remove auth token
function removeAuthToken() {
	localStorage.removeItem(STORAGE_KEYS.TOKEN);
	localStorage.removeItem(STORAGE_KEYS.USER);
}

// Helper: Get user data
function getUserData() {
	const userData = localStorage.getItem(STORAGE_KEYS.USER);
	return userData ? JSON.parse(userData) : null;
}

// Helper: Set user data
function setUserData(user) {
	localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user));
}

// Helper: Check if user is authenticated
function isAuthenticated() {
	return !!getAuthToken();
}

// Helper: Redirect to login if not authenticated
function requireAuth() {
	if (!isAuthenticated()) {
		window.location.href = "login.html";
	}
}

// Helper: Make API request
async function apiRequest(url, options = {}) {
	const token = getAuthToken();

	const headers = {
		"Content-Type": "application/json",
		...options.headers,
	};

	if (token) {
		headers["Authorization"] = `Bearer ${token}`;
	}

	try {
		const response = await fetch(`${url}`, {
			...options,
			headers,
		});

		const data = await response.json();

		if (!response.ok) {
			throw new Error(data.message || "Request failed");
		}

		return data;
	} catch (error) {
		showMessage(error.message || "API Request Error:", error);
		throw error;
	}
}

// Helper: Show message
function showMessage(message, type = "success") {
	const toast = document.createElement("div");
	toast.className = `toast toast-${type}`;
	toast.textContent = message;
	toast.style.cssText = `
		position: fixed;
		top: 20px;
		right: 10px;
        left: 10px;
		padding: 16px 24px;
		background: ${
			type === "success" ? "#10b981" : type === "error" ? "#ef4444" : "#f59e0b"
		};
		color: white;
		border-radius: 8px;
		box-shadow: 0 4px 6px rgba(0,0,0,0.1);
		z-index: 10000;
		animation: slideIn 0.3s ease-out;
	`;

	document.body.appendChild(toast);

	setTimeout(() => {
		toast.style.animation = "slideOut 0.3s ease-out";
		setTimeout(() => toast.remove(), 300);
	}, 3000);
}

// Helper: Get user initials
function getUserInitials(firstName, lastName) {
	const first = firstName ? firstName.charAt(0).toUpperCase() : "";
	const last = lastName ? lastName.charAt(0).toUpperCase() : "";
	return first + last || "?";
}

// Helper: Format time
function formatTime(date) {
	return new Date(date).toLocaleTimeString("en-US", {
		hour: "2-digit",
		minute: "2-digit",
	});
}

// Helper: Format date
function formatDate(date) {
	return new Date(date).toLocaleDateString("en-US", {
		weekday: "long",
		year: "numeric",
		month: "short",
		day: "numeric",
	});
}

// Helper: Calculate time difference in minutes
function calculateTimeDifference(start, end) {
	const startTime = new Date(start);
	const endTime = new Date(end);
	const diff = endTime - startTime;
	return Math.floor(diff / 1000 / 60);
}

// Helper: Format duration
function formatDuration(minutes) {
	const hours = Math.floor(minutes / 60);
	const mins = minutes % 60;
	return `${hours}h ${mins}m`;
}
