"use client";

interface LastSeenProps {
  lastonlineAt: Date | string | null;
}

function formatLastSeen(lastonlineAt: Date | string | null): string | null {
  if (!lastonlineAt) return null;
  const lastOnline = new Date(lastonlineAt);
  const diff = Date.now() - lastOnline.getTime();
  const minutes = Math.floor(diff / 60000);

  if (minutes < 5) return "Online now";
  if (minutes < 60) return `Last seen ${minutes} min ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `Last seen ${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `Last seen ${days}d ago`;
  if (days < 30) return `Last seen ${Math.floor(days / 7)}w ago`;
  // R15 E.5: previously returned null past 30 days, which collapsed the
  // chat header / profile subtitle. Render an explicit "Inactive" so the
  // layout stays stable.
  return "Inactive";
}

export default function LastSeen({ lastonlineAt }: LastSeenProps) {
  const text = formatLastSeen(lastonlineAt);
  if (!text) return null;

  const isOnline = text === "Online now";

  return (
    <span
      className={`inline-flex items-center gap-1.5 text-sm ${
        isOnline ? "text-green-400" : "text-text-muted"
      }`}
    >
      {isOnline && (
        <span className="relative flex h-2 w-2">
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-green-400" />
        </span>
      )}
      {!isOnline && (
        <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      )}
      {text}
    </span>
  );
}
