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

import { Bot, User, Headset, AlertCircle } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { ConversationMessage } from '../lib/types';

interface MessageBubbleProps {
  message: ConversationMessage;
}

function formatTime(date: Date | string, locale: string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  return d.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
}

export function MessageBubble({ message }: MessageBubbleProps) {
  const { t, locale } = useTranslation();

  if (message.role === 'system') {
    return (
      <div className="flex items-center justify-center my-3" data-testid={`msg-${message.id}`}>
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-gray-100 text-xs text-gray-600">
          <AlertCircle size={12} />
          <span>{t(`conversations.systemEvent.${message.content}`)}</span>
        </div>
      </div>
    );
  }

  const isVisitor = message.role === 'user';
  const isOperator = message.role === 'operator';

  const icon = isVisitor ? <User size={14} /> : isOperator ? <Headset size={14} /> : <Bot size={14} />;
  const authorLabel = isVisitor
    ? t('conversations.author.visitor')
    : isOperator
      ? message.operatorName ?? t('conversations.author.operator')
      : t('conversations.author.assistant');

  const bubbleColor = isVisitor
    ? 'bg-slate-100 text-slate-900'
    : isOperator
      ? 'bg-violet-600 text-white'
      : 'bg-emerald-600 text-white';

  const alignment = isVisitor ? 'items-start' : 'items-end';
  const bubbleAlignment = isVisitor ? 'self-start' : 'self-end';
  const iconBg = isVisitor ? 'bg-slate-200 text-slate-600' : isOperator ? 'bg-violet-100 text-violet-700' : 'bg-emerald-100 text-emerald-700';

  return (
    <div className={`flex flex-col ${alignment} gap-1 my-2`} data-testid={`msg-${message.id}`}>
      <div className={`flex items-center gap-1.5 text-xs text-gray-500 ${bubbleAlignment}`}>
        <span className={`inline-flex items-center justify-center w-5 h-5 rounded-full ${iconBg}`}>{icon}</span>
        <span className="font-medium">{authorLabel}</span>
        <span>·</span>
        <span>{formatTime(message.createdAt, locale)}</span>
      </div>
      <div className={`max-w-[70%] px-3 py-2 rounded-2xl text-sm whitespace-pre-wrap break-words ${bubbleColor} ${bubbleAlignment}`}>
        {message.content}
      </div>
    </div>
  );
}
