import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import ErrorBoundary from './ErrorBoundary';
import CodeBlock from './CodeBlock';

/**
 * SafeMarkdown component that wraps ReactMarkdown with error handling
 * Displays raw content as fallback if markdown parsing fails
 */
const SafeMarkdown = ({ content, className = 'markdown-content' }) => {
    // Fallback UI that shows raw content when ReactMarkdown fails
    const renderFallback = (error) => {
        console.error('Markdown rendering error:', error);
        return (
            <div className={`${className} markdown-fallback`}>
                <p className='text-danger mb-2'>
                    <small>Error rendering markdown. Showing raw content:</small>
                </p>
                <div className='p-2 border rounded'>{content}</div>
            </div>
        );
    };

    return (
        <ErrorBoundary fallback={renderFallback}>
            <ReactMarkdown
                remarkPlugins={[remarkGfm]}
                components={{
                    // Apply the className to the root element
                    root: ({ node, ...props }) => <div className={className} {...props} />,
                    code({ node, inline, className: codeClassName, children, ...props }) {
                        const match = /language-(\w+)/.exec(codeClassName || '');
                        return !inline && match ? (
                            <CodeBlock language={match[1]} value={String(children).replace(/\n$/, '')} />
                        ) : (
                            <code className={codeClassName} {...props}>
                                {children}
                            </code>
                        );
                    },
                }}
            >
                {content}
            </ReactMarkdown>
        </ErrorBoundary>
    );
};

export default SafeMarkdown;
