import { Text } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useOnlineUsers } from '../../hooks/useOnlineUsers';
import { useLastSeenBatch } from '../../hooks/useLastSeenBatch';

type Props = {
  userId: string;
};

function formatLastSeen(ts: string, t: (key: string, opts?: Record<string, unknown>) => string): string {
  const diff = Date.now() - new Date(ts).getTime();
  if (diff < 60_000) return t('presence.just_now');
  if (diff < 3_600_000) return t('presence.minutes_ago', { minutes: Math.floor(diff / 60_000) });
  if (diff < 86_400_000) return t('presence.hours_ago', { hours: Math.floor(diff / 3_600_000) });
  return t('presence.days_ago', { days: Math.floor(diff / 86_400_000) });
}

export function ChatHeaderStatus({ userId }: Props) {
  const { t } = useTranslation();
  const { isOnline } = useOnlineUsers();
  const lastSeenMap = useLastSeenBatch(isOnline(userId) ? [] : [userId]);
  const online = isOnline(userId);

  if (online) {
    // User-Wunsch: „Online"-Text zeigen, aber NICHT grün (Dot im Avatar reicht
    // als Farb-Signal). Neutraler `textMuted`-Grau-Ton.
    return (
      <Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
        {t('presence.online')}
      </Text>
    );
  }

  const lastSeen = lastSeenMap[userId];
  if (!lastSeen) return null;

  return (
    <Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
      {formatLastSeen(lastSeen, t)}
    </Text>
  );
}
