export function formatLastActive(
  value?: string | Date | null,
  options?: { emptyLabel?: string }
): string {
  if (!value) return options?.emptyLabel ?? '';

  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return options?.emptyLabel ?? '';

  const now = Date.now();
  const diffMs = Math.max(0, now - date.getTime());
  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diffMs < 2 * minute) return 'Active now';
  if (diffMs < hour) {
    const mins = Math.max(1, Math.floor(diffMs / minute));
    return `Active ${mins}m ago`;
  }
  if (diffMs < day) {
    const hours = Math.max(1, Math.floor(diffMs / hour));
    return `Active ${hours}h ago`;
  }
  if (diffMs < 7 * day) {
    const days = Math.max(1, Math.floor(diffMs / day));
    return days === 1 ? 'Active yesterday' : `Active ${days}d ago`;
  }

  return `Last active ${date.toLocaleDateString('en-PH', { month: 'short', day: 'numeric' })}`;
}

export function isRecentlyActive(value?: string | Date | null, withinMinutes = 5): boolean {
  if (!value) return false;
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return false;
  return Date.now() - date.getTime() <= withinMinutes * 60 * 1000;
}
