function displayName(user) {
	return user.display_name || user.username || user.jellyfin_id;
}

function splitValues(value) {
	return String(value || "")
		.split(",")
		.map((part) => part.trim())
		.filter(Boolean);
}

function syncStatus(user) {
	if (
		user.jellyseerr_user_id !== null &&
		user.jellyseerr_user_id !== undefined
	) {
		return "Linked with Jellyseerr";
	}
	if (String(user.source_summary || user.source || "").includes("jellyseerr")) {
		return "Enriched via Jellyseerr";
	}
	return "Jellyfin only";
}

export function buildUserDrawerModel(user) {
	const title = displayName(user);
	const subtitle = user.email || "No email address available";
	const permissions = splitValues(user.permissions_label);
	const source = String(user.source_summary || user.source || "jellyfin");
	const roleLabel = user.role
		? user.role.charAt(0).toUpperCase() + user.role.slice(1)
		: "Unknown";
	const contactLabel = user.contactable ? "Contactable" : "Read-only";
	const contactDescription = user.contactable
		? "An email address is available for future communication workflows."
		: "No direct contact route is available yet.";

	return {
		title,
		subtitle,
		contactState: {
			label: contactLabel,
			description: contactDescription,
		},
		contactActions: [
			{
				label: "Email",
				enabled: false,
				hint: user.contactable
					? "Email action is planned for a future release."
					: "Disabled until an email address is available.",
			},
			{
				label: "Notify",
				enabled: false,
				hint: "Notification workflows are not wired up yet.",
			},
		],
		identity: [
			{ label: "Email", value: user.email || "—" },
			{ label: "Email source", value: user.email_source || "none" },
			{ label: "Avatar source", value: user.avatar_source || "none" },
			{ label: "Jellyfin ID", value: user.jellyfin_id },
			{ label: "Name source", value: user.name_source || "jellyfin" },
			{ label: "Access source", value: user.access_source || "none" },
			{
				label: "Jellyseerr user ID",
				value:
					user.jellyseerr_user_id === null ||
					user.jellyseerr_user_id === undefined
						? "Not linked"
						: `#${user.jellyseerr_user_id}`,
			},
			{ label: "Account type", value: user.user_type_label || "unknown" },
			{ label: "Role", value: roleLabel },
			{ label: "Permissions", value: permissions.join(", ") || "none" },
			{
				label: "Requests",
				value:
					user.request_count === null || user.request_count === undefined
						? "—"
						: String(user.request_count),
			},
			{ label: "Source", value: source },
		],
		permissions,
		syncStatus: syncStatus(user),
		source,
	};
}
