import ReactMarkdown from 'react-markdown';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import { cn } from '@/lib/utils';

interface MarkdownRendererProps {
  content: string;
  className?: string;
}

// Custom sanitization schema with enhanced security
const customSchema = {
  ...defaultSchema,
  attributes: {
    ...defaultSchema.attributes,
    a: [
      ...(defaultSchema.attributes?.a || []),
      ['rel', 'noopener', 'noreferrer'],
      ['target', '_blank']
    ],
    img: [
      ...(defaultSchema.attributes?.img || []),
      ['loading', 'lazy'],
      ['referrerpolicy', 'no-referrer']
    ]
  }
};

/**
 * Secure Markdown Renderer with XSS Protection
 * 
 * Security features:
 * - Sanitizes all user-generated HTML using rehype-sanitize
 * - Strips all raw HTML tags (skipHtml=true)
 * - Enforces noopener noreferrer on all links
 * - Adds lazy loading to images
 * - Sets referrer policy to prevent data leakage
 * 
 * @see docs/SECURITY.md for markdown security policy
 */
export function MarkdownRenderer({ content, className }: MarkdownRendererProps) {
  return (
    <div
      className={cn(
        'prose dark:prose-invert max-w-none',
        'prose-headings:font-bold prose-headings:tracking-tight',
        'prose-h1:text-4xl prose-h2:text-3xl prose-h3:text-2xl',
        'prose-p:text-base prose-p:leading-relaxed',
        'prose-a:text-primary prose-a:no-underline hover:prose-a:underline',
        'prose-strong:text-foreground prose-strong:font-semibold',
        'prose-code:bg-muted prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm',
        'prose-pre:bg-muted prose-pre:border prose-pre:border-border',
        'prose-blockquote:border-l-4 prose-blockquote:border-primary prose-blockquote:italic',
        'prose-img:rounded-lg prose-img:shadow-lg',
        'prose-hr:border-border',
        'prose-ul:list-disc prose-ol:list-decimal',
        className
      )}
    >
      <ReactMarkdown 
        rehypePlugins={[[rehypeSanitize, customSchema]]}
        skipHtml={true}
        components={{
          a: ({node, ...props}) => (
            <a {...props} rel="noopener noreferrer" target="_blank" />
          ),
          img: ({node, ...props}) => (
            <img {...props} loading="lazy" referrerPolicy="no-referrer" />
          )
        }}
      >
        {content}
      </ReactMarkdown>
    </div>
  );
}
