// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * "Captured this session" block — renders inside VisitorContextPanel when
 * the visitor has submitted the contact-capture form for the current
 * conversation. Polls /captured-contact every 5 s via useCapturedContact.
 *
 * When `captured === null` (or pending) the component returns null so the
 * surrounding panel stays compact. No empty-state copy.
 */

import { useTranslation } from '@/i18n/TranslationProvider';
import { useCapturedContact } from '../hooks/useCapturedContact';

interface CapturedContactBlockProps {
  conversationId: string;
}

function relativeWhen(date: string, locale: string): string {
  const target = new Date(date);
  const diffMs = Date.now() - target.getTime();
  const minutes = Math.floor(diffMs / 60_000);
  if (minutes < 1) return locale === 'de' ? 'gerade eben' : 'just now';
  if (minutes < 60) return locale === 'de' ? `vor ${minutes} Min.` : `${minutes} min ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return locale === 'de' ? `vor ${hours} Std.` : `${hours} h ago`;
  const days = Math.floor(hours / 24);
  return locale === 'de' ? `vor ${days} Tagen` : `${days} d ago`;
}

export function CapturedContactBlock({ conversationId }: CapturedContactBlockProps) {
  const { t, locale } = useTranslation();
  const { data } = useCapturedContact(conversationId);

  if (!data || !data.captured) return null;

  const { values, capturedAt } = data.captured;
  const entries = Object.entries(values);

  return (
    <section
      data-testid="captured-contact-block"
      className="px-5 py-4 border-b border-gray-100 bg-emerald-50/40"
    >
      <h3 className="text-[10px] uppercase font-bold tracking-wider text-emerald-700 mb-2">
        {t('conversations.captured.title')}
      </h3>
      <div className="space-y-1">
        {entries.map(([key, value]) => (
          <div
            key={key}
            data-testid={`captured-${key}`}
            className="flex items-baseline justify-between gap-2 text-xs"
          >
            <span className="text-gray-500 capitalize shrink-0">{key}</span>
            <span className="text-gray-900 font-medium text-right truncate">{value}</span>
          </div>
        ))}
      </div>
      <small className="block mt-2 text-[10px] text-gray-400" data-testid="captured-at">
        {t('conversations.captured.capturedAt', { when: relativeWhen(capturedAt, locale) })}
      </small>
    </section>
  );
}
