import { useEffect, useState } from "react";

export function formatRelativeTime(date: Date | string): string {
  const now = new Date();
  const then = new Date(date);
  const diffMs = now.getTime() - then.getTime();
  const diffMinutes = Math.floor(diffMs / 60000);

  if (diffMinutes < 1) return "Ahora";
  if (diffMinutes < 60) return `Hace ${diffMinutes} min`;

  const diffHours = Math.floor(diffMinutes / 60);
  if (diffHours < 24) return `Hace ${diffHours}h`;

  const diffDays = Math.floor(diffHours / 24);
  return `Hace ${diffDays}d`;
}

export function RelativeTime({ date }: { date: Date | string }) {
  const [label, setLabel] = useState(() => formatRelativeTime(date));

  useEffect(() => {
    setLabel(formatRelativeTime(date));
    const interval = setInterval(() => {
      setLabel(formatRelativeTime(date));
    }, 30_000);
    return () => clearInterval(interval);
  }, [date]);

  return label;
}
