// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)

import { Globe } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { ConversationListItem as ConvListItem } from '../lib/types';
import { StatusBadge } from './StatusBadge';
import { VisitorAvatar } from './VisitorAvatar';
import { WaitTimeBadge } from './WaitTimeBadge';
import { visitorWaitMsItem, urgencyFor } from '../lib/waitTime';

interface ConversationListItemProps {
  conversation: ConvListItem;
  selected: boolean;
  onSelect: () => void;
}

function lastMessagePreview(conv: ConvListItem): string {
  const last = conv.lastMessage;
  if (!last) return '';
  const trimmed = last.content.length > 80 ? `${last.content.slice(0, 80)}…` : last.content;
  if (last.role === 'operator') return `↳ ${trimmed}`;
  if (last.role === 'assistant') return `AI: ${trimmed}`;
  if (last.role === 'system') return `· ${trimmed}`;
  return trimmed;
}

function formatRelative(date: Date | string, locale: string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  const diffMs = Date.now() - d.getTime();
  const min = Math.floor(diffMs / 60_000);
  if (min < 1) return locale === 'de' ? 'jetzt' : 'now';
  if (min < 60) return `${min} min`;
  const hours = Math.floor(min / 60);
  if (hours < 24) return `${hours} h`;
  return d.toLocaleDateString(locale);
}

export function ConversationListItem({ conversation, selected, onSelect }: ConversationListItemProps) {
  const { locale } = useTranslation();
  const waitMs = visitorWaitMsItem(conversation);
  const urgency = urgencyFor(waitMs);
  return (
    <button
      type="button"
      onClick={onSelect}
      data-testid={`conv-list-item-${conversation.id}`}
      className={`w-full text-left px-3 py-3 border-b border-gray-100 hover:bg-slate-50 transition-colors flex gap-3 ${
        selected ? 'bg-emerald-50/60 border-l-4 border-l-emerald-500' : 'border-l-4 border-l-transparent'
      }`}
    >
      <VisitorAvatar handle={conversation.visitorRef} size="md" />
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2 mb-1">
          <span className="text-sm font-semibold text-gray-900 truncate">{conversation.visitorRef}</span>
          <span className="text-xs text-gray-400 shrink-0">{formatRelative(conversation.lastActivityAt, locale)}</span>
        </div>
        <div className="flex flex-wrap items-center gap-1.5 mb-1.5">
          <StatusBadge status={conversation.status} />
          {waitMs > 0 && <WaitTimeBadge waitMs={waitMs} urgency={urgency} />}
          <div className="flex items-center gap-1 text-xs text-gray-500 min-w-0 ml-auto">
            <Globe size={12} className="shrink-0" />
            <span className="truncate max-w-[120px]">{conversation.tenantName}</span>
          </div>
          {conversation.unreadByOperator > 0 && (
            <span
              className="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-red-500 text-white text-[10px] font-bold"
              data-testid={`unread-${conversation.id}`}
            >
              {conversation.unreadByOperator}
            </span>
          )}
        </div>
        <p className="text-xs text-gray-600 line-clamp-2">{lastMessagePreview(conversation)}</p>
      </div>
    </button>
  );
}
