/**
 * Date Formatting Utilities
 * Story 3.1: Human-readable relative dates for history feed
 */

/**
 * Format a timestamp as a relative date string
 * @param timestamp - The timestamp to format (milliseconds since epoch)
 * @returns Human-readable relative date string
 *
 * Examples:
 * - Today: "Today"
 * - Yesterday: "Yesterday"
 * - 6 days ago: "6 days ago"
 * - 2 weeks ago: "2 weeks ago"
 * - Older: "Jan 15" or "Jan 15, 2024"
 */
export function formatRelativeDate(timestamp: number): string {
  const now = Date.now();
  const diff = now - timestamp;

  // Handle invalid or future timestamps
  if (diff < 0) {
    return 'Just now';
  }

  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  // Today
  if (days === 0) {
    return 'Today';
  }

  // Yesterday
  if (days === 1) {
    return 'Yesterday';
  }

  // Less than a week
  if (days < 7) {
    return `${days} days ago`;
  }

  // Less than a month - show weeks
  if (days < 30) {
    const weeks = Math.floor(days / 7);
    return `${weeks} week${weeks > 1 ? 's' : ''} ago`;
  }

  // Full date for older posts
  const date = new Date(timestamp);
  const currentYear = new Date().getFullYear();

  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: date.getFullYear() !== currentYear ? 'numeric' : undefined
  });
}

/**
 * Format a timestamp as a full date string
 * @param timestamp - The timestamp to format (milliseconds since epoch)
 * @returns Formatted date string (e.g., "January 15, 2024")
 */
export function formatFullDate(timestamp: number): string {
  const date = new Date(timestamp);
  return date.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric'
  });
}

/**
 * Format a timestamp as a short date string
 * @param timestamp - The timestamp to format (milliseconds since epoch)
 * @returns Short formatted date string (e.g., "Jan 15")
 */
export function formatShortDate(timestamp: number): string {
  const date = new Date(timestamp);
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric'
  });
}

/**
 * Format a timestamp as a time string
 * @param timestamp - The timestamp to format (milliseconds since epoch)
 * @returns Formatted time string (e.g., "2:30 PM")
 */
export function formatTime(timestamp: number): string {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
    hour12: true
  });
}
