/**
 * Friendly relative time formatter used throughout the support widget.
 * Only use this in browser context (components with effects, not during SSR).
 */
export function formatTimeAgo(date: Date | string): string {
	// Guard against SSR - return empty string or static fallback
	if (typeof window === "undefined") {
		return "";
	}

	const now = new Date();
	const messageDate = typeof date === "string" ? new Date(date) : date;
	const diffMs = now.getTime() - messageDate.getTime();
	const diffMins = Math.floor(diffMs / (1000 * 60));
	const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
	const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

	if (diffMins < 1) {
		return "now";
	}
	if (diffMins < 60) {
		return `${diffMins}m ago`;
	}
	if (diffHours < 24) {
		return `${diffHours}h ago`;
	}
	if (diffDays === 1) {
		return "Yesterday";
	}
	if (diffDays < 7) {
		return `${diffDays} days ago`;
	}
	if (diffDays < 30) {
		const weeks = Math.floor(diffDays / 7);
		return `${weeks} ${weeks === 1 ? "week" : "weeks"} ago`;
	}
	if (diffDays < 365) {
		const months = Math.floor(diffDays / 30);
		return `${months} ${months === 1 ? "month" : "months"} ago`;
	}
	const years = Math.floor(diffDays / 365);
	return `${years} ${years === 1 ? "year" : "years"} ago`;
}
