'use client';

import { cn } from '@/lib/utils';

// Deterministic color from string
const AVATAR_COLORS = [
  '#ef4444', '#f97316', '#eab308', '#22c55e', '#14b8a6',
  '#06b6d4', '#3b82f6', '#8b5cf6', '#a855f7', '#ec4899',
];

function hashColor(str: string) {
  let h = 0;
  for (let i = 0; i < str.length; i++) h = str.charCodeAt(i) + ((h << 5) - h);
  return AVATAR_COLORS[Math.abs(h) % AVATAR_COLORS.length];
}

function getInitials(name?: string | null) {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/);
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return parts[0].slice(0, 2).toUpperCase();
}

interface MessageBubbleProps {
  body: string;
  direction: 'inbound' | 'outbound';
  source: string;
  createdAt: string;
  contactName?: string | null;
  showAvatar?: boolean;
}

export function MessageBubble({ body, direction, source, createdAt, contactName, showAvatar = true }: MessageBubbleProps) {
  const isInbound = direction === 'inbound';
  const time = new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

  return (
    <div className={cn('flex gap-2 mb-3 max-w-[80%]', isInbound ? 'self-start' : 'self-end flex-row-reverse')}>
      {/* Avatar – only for inbound */}
      {isInbound && showAvatar ? (
        <div
          className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0 mt-auto"
          style={{ backgroundColor: hashColor(contactName || 'U') }}
        >
          {getInitials(contactName)}
        </div>
      ) : isInbound ? (
        <div className="w-8 flex-shrink-0" />
      ) : null}

      {/* Bubble */}
      <div
        className={cn(
          'px-4 py-2.5 rounded-2xl text-sm leading-relaxed break-words',
          isInbound
            ? 'bg-[#334155] text-slate-100 rounded-bl-md'
            : 'bg-gradient-to-br from-[#0891b2] to-[#06b6d4] text-white rounded-br-md'
        )}
      >
        <p className="whitespace-pre-wrap">{body}</p>
        <div className={cn('flex items-center gap-1.5 mt-1', isInbound ? 'justify-start' : 'justify-end')}>
          {!isInbound && source && (
            <span className="text-[10px] opacity-60 capitalize">{source}</span>
          )}
          <span className="text-[10px] opacity-50">{time}</span>
        </div>
      </div>
    </div>
  );
}

export { hashColor, getInitials, AVATAR_COLORS };
