import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

/**
 * Formats a timestamp as relative time (e.g., "2 minutes ago", "Yesterday")
 * @param {string} timestamp - ISO timestamp string
 * @returns {string} Formatted relative time
 */
export const formatTimestamp = (timestamp) => {
  if (!timestamp) return '';

  try {
    const date = dayjs(timestamp);
    if (!date.isValid()) return '';

    const now = dayjs();
    const diffInMinutes = now.diff(date, 'minute');
    const diffInHours = now.diff(date, 'hour');
    const diffInDays = now.diff(date, 'day');

    if (diffInMinutes < 1) return 'Just now';
    if (diffInMinutes < 60) return `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
    if (diffInHours < 24) return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
    if (diffInDays === 1) return 'Yesterday';
    if (diffInDays < 7) return date.format('dddd'); // Day name (e.g., "Monday")
    return date.format('MM/DD/YYYY');
  } catch (error) {
    console.error('formatTimestamp error:', error);
    return '';
  }
};
