import { useChatStore } from '@/stores/chatStore';
import { useMemo, type FC } from 'react';

type TypingIndicatorProps = {
  roomId: string;
};

export const TypingIndicator: FC<TypingIndicatorProps> = ({ roomId }) => {
  const { typingUsers } = useChatStore();

  const typingUsernames = useMemo(() => {
    if (!typingUsers[roomId]) return [];
    return Array.from(typingUsers[roomId]);
  }, [typingUsers, roomId]);

  if (typingUsernames.length === 0) return null;

  const formatTypingText = () => {
    if (typingUsernames.length === 1) {
      return `${typingUsernames[0]} is typing`;
    } else if (typingUsernames.length === 2) {
      return `${typingUsernames[0]} and ${typingUsernames[1]} are typing`;
    } else if (typingUsernames.length === 3) {
      return `${typingUsernames[0]}, ${typingUsernames[1]} and ${typingUsernames[2]} are typing`;
    } else {
      return `${typingUsernames.length} people are typing...`;
    }
  };

  return (
    <div className="text-xs text-gray-500 animate-pulse h-5 px-4">
      {formatTypingText()}
      <span className="inline-flex">
        <span className="animate-bounce">.</span>
        <span className="animate-bounce delay-100">.</span>
        <span className="animate-bounce delay-200">.</span>
      </span>
    </div>
  );
};
