import { cn } from '@/lib/utils';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

interface ChatBubbleProps {
    role: 'user' | 'assistant' | 'system';
    content: string;
}

export function ChatBubble({ role, content }: ChatBubbleProps) {
    const isUser = role === 'user';

    return (
        <div className={cn(
            "flex w-full mb-4",
            isUser ? "justify-end" : "justify-start"
        )}>
            <div className={cn(
                "max-w-[80%] rounded-2xl px-4 py-3 text-sm leading-relaxed shadow-sm",
                isUser
                    ? "bg-primary text-primary-foreground rounded-tr-sm"
                    : "bg-card border border-border text-card-foreground rounded-tl-sm"
            )}>
                {/* Render Markdown safely */}
                <div className="prose prose-sm dark:prose-invert max-w-none break-words">
                    <ReactMarkdown
                        remarkPlugins={[remarkGfm]}
                        components={{
                            p: ({ node, ...props }) => <p className="mb-1 last:mb-0" {...props} />,
                            pre: ({ node, ...props }) => (
                                <div className="max-w-full overflow-x-auto my-2 rounded bg-black/5 p-2 scrollbar-thin scrollbar-thumb-gray-300">
                                    <pre {...props} className="whitespace-pre" />
                                </div>
                            ),
                            code: ({ node, className, ...props }) => (
                                <code
                                    className={cn(
                                        "font-mono text-xs break-words",
                                        !className && "bg-black/5 px-1 py-0.5 rounded",
                                        className
                                    )}
                                    {...props}
                                />
                            )
                        }}
                    >
                        {String(content)}
                    </ReactMarkdown>
                </div>
            </div>
        </div>
    );
}
