// utils/time.js

/**
 * Human-readable "X time ago" from ISO string
 * @param {string} isoString - e.g. "2025-03-10T14:30:00Z"
 * @returns {string} e.g. "2 hours ago"
 */
export function simpleTimeAgo(input) {
  if (!input) return 'never';

  let date;
  if (input instanceof Date) {
    date = input;
  } else if (typeof input === 'number') {
    date = new Date(input);
  } else if (typeof input === 'string') {
    let cleaned = input.trim();
    // If no timezone (no Z or offset), assume UTC and append Z
    if (!cleaned.endsWith('Z') && !cleaned.match(/[+-]\d{2}:\d{2}$/)) {
      cleaned += 'Z';
      console.log('[TIME] Appended Z to timestamp (assumed UTC):', cleaned);
    }
    date = new Date(cleaned);
  } else {
    console.log('[TIME] Invalid input type to simpleTimeAgo:', typeof input, input);
    return 'invalid';
  }

  if (isNaN(date.getTime())) {
    console.log('[TIME] Invalid date parsed from:', input);
    return 'invalid';
  }

  const now = Date.now();
  const diffMs = now - date.getTime();

  // Small clock skew tolerance (< 5 minutes future → treat as "just now")
  if (diffMs < 0 && diffMs > -300000) {
    return 'just now';
  }

  // Future (real future)
  if (diffMs < 0) {
    const futureMs = -diffMs;
    const futureSeconds = Math.floor(futureMs / 1000);
    const futureMinutes = Math.floor(futureSeconds / 60);
    const futureHours = Math.floor(futureMinutes / 60);
    const futureDays = Math.floor(futureHours / 24);

    if (futureSeconds < 60) return `in ${futureSeconds} seconds`;
    if (futureMinutes < 60) return `in ${futureMinutes} minutes`;
    if (futureHours < 24) return `in ${futureHours} hours`;
    return `in ${futureDays} days`;
  }

  // Past
  const seconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (seconds < 60) return `${seconds} seconds ago`;
  if (minutes < 60) return `${minutes} minutes ago`;
  if (hours < 24) return `${hours} hours ago`;
  if (days < 30) return `${days} days ago`;

  return date.toLocaleDateString(); // fallback
}