// // src/components/CustomMarkdownRenderer.tsx (or wherever you place it)

// import React from 'react';
// import ReactMarkdown from 'react-markdown';
// import remarkGfm from 'remark-gfm';
// import rehypeRaw from 'rehype-raw'; // Optional: Include only if your markdown may contain raw HTML
// import rehypeSanitize from 'rehype-sanitize'; // Recommended for security if using rehypeRaw or untrusted sources
// import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
// import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism'; // Dark theme; swap to oneLight for light mode

// type CustomMarkdownRendererProps = {
//     markdown: string; // The markdown content to render
//     allowRawHtml?: boolean; // Optional: Toggle rehypeRaw + sanitize (default: false for safety)
//     className?: string; // Optional: Additional classes for the wrapper
// };

// const CustomMarkdownRenderer: React.FC<CustomMarkdownRendererProps> = ({
//     markdown,
//     allowRawHtml = false,
//     className = '',
// }) => {

//     function preprocessPolicyText(raw: string): string {
//         let text = raw;

//         // 1. Replace known garbage patterns
//         text = text.replace(/GLYPH<c=0,font=\/BAAAAA\+OpenSans-Regular>/g, '→ ');
//         text = text.replace(/&amp;/g, '&');

//         // 2. Force section headers to become real markdown headers
//         text = text.replace(
//             /(Section: \d+\.\s*[A-Za-z &/]+(\s*\([^)]+\))?)/g,
//             (match) => `\n\n### ${match}\n`
//         );

//         // 3. Convert numbered lines that look like lists
//         text = text.replace(/^(\d+\.\s+)/gm, '- $1');

//         // 4. Improve bullet detection
//         text = text.replace(/^\s*-\s*/gm, '- ');

//         // 5. Add line breaks before common strong markers
//         text = text.replace(/\*\*(.*?)\*\*/g, '\n\n**$1**\n');

//         return text.trim();
//     }
//     return (
//         <div className={`prose prose-invert max-w-none ${className}`}>
//             <ReactMarkdown
//                 remarkPlugins={[remarkGfm]}
//                 rehypePlugins={allowRawHtml ? [rehypeRaw, rehypeSanitize] : [rehypeSanitize]} // Secure by default
//                 components={{
//                     // Custom code block with syntax highlighting
//                     code({ node, inline, className, children, ...props }: any) {
//                         const match = /language-(\w+)/.exec(className || '');
//                         return !inline && match ? (
//                             <SyntaxHighlighter
//                                 style={oneDark}
//                                 language={match[1]}
//                                 PreTag="div"
//                                 customStyle={{
//                                     margin: '1.5rem 0',
//                                     borderRadius: '0.5rem',
//                                     fontSize: '0.95rem',
//                                 }}
//                                 {...props}
//                             >
//                                 {String(children).replace(/\n$/, '')}
//                             </SyntaxHighlighter>
//                         ) : (
//                             <code className="bg-gray-800/50 px-1.5 py-0.5 rounded text-pink-300" {...props}>
//                                 {children}
//                             </code>
//                         );
//                     },
//                     // Custom inline code for status badges (e.g., `COMPLIANT`)
//                     // Note: ReactMarkdown uses 'code' for both inline and block; we handle inline here separately
//                     // But for precision, this overrides inline code
//                     // If needed, adjust based on testing
//                     // ...
//                     // (The inlineCode override in your original code seems to be a typo; ReactMarkdown's components use 'code' for both.
//                     // To distinguish, we check 'inline' in the code component above. For pure inline, it's already handled.)
//                     // If you need separate inline logic, combine it in the code component as above.

//                     h1: ({ children }) => (
//                         <h1 className="text-2xl font-bold mt-8 mb-4 border-b border-gray-700 pb-2">{children}</h1>
//                     ),
//                     h2: ({ children }) => (
//                         <h2 className="text-xl font-semibold mt-6 mb-3 text-blue-300">{children}</h2>
//                     ),
//                     h3: ({ children }) => (
//                         <h3 className="text-lg font-medium mt-5 mb-2.5">{children}</h3>
//                     ),
//                     hr: () => <hr className="my-6 border-gray-700" />,
//                     table: ({ children }) => (
//                         <div className="overflow-x-auto my-6">
//                             <table className="min-w-full border-collapse">{children}</table>
//                         </div>
//                     ),
//                     th: ({ children }) => (
//                         <th className="border border-gray-600 bg-gray-800/50 px-4 py-2 text-left font-semibold">
//                             {children}
//                         </th>
//                     ),
//                     td: ({ children }) => (
//                         <td className="border border-gray-700 px-4 py-2">{children}</td>
//                     ),
//                     ul: ({ children }) => <ul className="list-disc pl-6 my-3 space-y-1.5">{children}</ul>,
//                     ol: ({ children }) => <ol className="list-decimal pl-6 my-3 space-y-1.5">{children}</ol>,
//                     li: ({ children }) => <li className="text-gray-300">{children}</li>,
//                     p: ({ children }) => <p className="my-3 leading-relaxed text-gray-300">{children}</p>,
//                     strong: ({ children }) => <strong className="font-semibold text-white">{children}</strong>,
//                     em: ({ children }) => <em className="italic text-gray-400">{children}</em>,
//                 }}
//             >
//                 {markdown}
//             </ReactMarkdown>
//         </div>
//     );
// };

// export default CustomMarkdownRenderer;
// src/components/CustomMarkdownRenderer.tsx

// import React from 'react';
// import ReactMarkdown from 'react-markdown';
// import remarkGfm from 'remark-gfm';
// import rehypeSanitize from 'rehype-sanitize';      // always include for safety
// import rehypeRaw from 'rehype-raw';                // optional – only enable when needed
// import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
// import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
// import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'; // ← added light theme

// interface CustomMarkdownRendererProps {
//     markdown: string;
//     allowRawHtml?: boolean;       // default = false (safer)
//     className?: string;
//     // You can pass theme explicitly if you want – but usually better to use CSS variables
//     forceTheme?: 'light' | 'dark';
//     textAlign?: 'left' | 'center' | 'right';
// }

// const CustomMarkdownRenderer: React.FC<CustomMarkdownRendererProps> = ({
//     markdown,
//     allowRawHtml = false,
//     className = '',
//     forceTheme,
//     textAlign = 'left',
// }) => {
//     // Simple preprocess to clean up your specific garbage patterns
//     const preprocess = (raw: string): string => {
//         let text = raw;

//         // Replace known artifacts from your sample data
//         text = text?.replace(/GLYPH<c=0,font=\/BAAAAA\+OpenSans-Regular>/g, '→ ');
//         text = text?.replace(/&amp;/g, '&');

//         // Turn "Section: X.Y ..." into proper markdown headers
//         text = text?.replace(
//             /(Section:\s*\d+\.\s*[A-Za-z &()/]+(\s*\([^)]+\))?)/g,
//             '\n\n### $1\n'
//         );

//         // Convert numbered steps to markdown list items
//         text = text?.replace(/^(\d+\.\s+)/gm, '- $1');

//         // Normalize bullet points
//         text = text?.replace(/^\s*-\s*/gm, '- ');

//         // Ensure bold text gets breathing room
//         text = text?.replace(/\*\*(.*?)\*\*/g, '\n\n**$1**\n');

//         return text.trim();
//     };

//     const processedMarkdown = preprocess(markdown);

//     // Decide which syntax highlighter theme to use
//     const isDark = forceTheme === 'dark' || (!forceTheme && document.documentElement.getAttribute('data-theme') !== 'light');
//     const syntaxTheme = isDark ? oneDark : oneLight;

//     return (
//         <div className={`markdown-content prose prose-invert max-w-none ${textAlign === "left" ? "text-left" : textAlign === "center" ? "text-center" : "text-right"} ${className}`}>
//             <ReactMarkdown
//                 remarkPlugins={[remarkGfm]}
//                 rehypePlugins={allowRawHtml ? [rehypeRaw, rehypeSanitize] : [rehypeSanitize]}
//                 components={{
//                     // ────────────────────────────────────────────────────────────────
//                     // Code blocks (multi-line)
//                     code({ node, inline, className, children, ...props }: any) {
//                         const match = /language-(\w+)/.exec(className || '');
//                         if (!inline && match) {
//                             return (
//                                 <SyntaxHighlighter
//                                     style={syntaxTheme}
//                                     language={match[1]}
//                                     PreTag="div"
//                                     dir="ltr"
//                                     customStyle={{
//                                         margin: '1.25rem 0',
//                                         borderRadius: '0.5rem',
//                                         fontSize: '0.94rem',
//                                         backgroundColor: 'var(--secondary25)',
//                                     }}
//                                     {...props}
//                                 >
//                                     {String(children).replace(/\n$/, '')}
//                                 </SyntaxHighlighter>
//                             );
//                         }

//                         // Inline code (e.g. `COMPLIANT`, `PARTIAL`, variable names)
//                         const text = String(children).trim();

//                         let textColor = 'var(--grey92)';
//                         let bgColor = 'var(--secondary25)';

//                         if (text?.includes('COMPLIANT')) {
//                             textColor = 'var(--primary)';           // green-ish from your theme
//                             bgColor = 'color-mix(in srgb, var(--primary) 15%, transparent)';
//                         } else if (text?.includes('PARTIAL')) {
//                             textColor = 'var(--primary-c5)';        // lighter green/teal from your theme
//                             bgColor = 'color-mix(in srgb, var(--primary-c5) 20%, transparent)';
//                         } else if (text?.includes('NON-COMPLIANT') || text?.includes('GAP')) {
//                             textColor = 'var(--red)';               // your defined red
//                             bgColor = 'color-mix(in srgb, var(--red) 20%, transparent)';
//                         } else {
//                             // fallback for other inline code
//                             textColor = 'var(--primary-c1)';
//                             bgColor = 'var(--secondary25)';
//                         }
//                         return (
//                             <code
//                                 className={`font-medium px-1.5 py-0.5 rounded `}
//                                 {...props}
//                             >
//                                 {text}
//                             </code>
//                         );
//                     },

//                     // Headings – use project colors
//                     h1: ({ children }) => (
//                         <h1 className="text-2xl sm:text-3xl font-bold mt-10 mb-5 border-b border-[var(--grey32)] pb-2.5 text-[var(--light)] text-start">
//                             {children}
//                         </h1>
//                     ),
//                     h2: ({ children }) => (
//                         <h2 className="text-xl sm:text-2xl font-semibold mt-8 mb-4 text-[var(--primary)] text-start">
//                             {children}
//                         </h2>
//                     ),
//                     h3: ({ children }) => (
//                         <h3 className="text-lg sm:text-xl font-medium mt-7 mb-3 text-[var(--grey99)] text-start">
//                             {children}
//                         </h3>
//                     ),


//                     hr: () => <hr className="my-8 border-[var(--grey32)]" />,

//                     // Tables
//                     table: ({ children }) => (
//                         <div className="overflow-x-auto my-6 rounded-lg border border-[var(--grey32)]">
//                             <table className="min-w-full border-collapse">{children}</table>
//                         </div>
//                     ),
//                     th: ({ children }) => (
//                         <th className="border border-[var(--grey32)] bg-[var(--secondary25)] px-4 py-2.5 text-start font-semibold text-[var(--grey99)]">
//                             {children}
//                         </th>
//                     ),
//                     td: ({ children }) => (
//                         <td className="border border-[var(--grey32)] px-4 py-2.5 text-start text-[var(--grey92)]">
//                             {children}
//                         </td>
//                     ),


//                     // Lists
//                     ul: ({ children }) => (
//                         <ul className="list-disc ps-6 my-4 space-y-2 text-[var(--grey92)]">
//                             {children}
//                         </ul>
//                     ),
//                     ol: ({ children }) => (
//                         <ol className="list-decimal ps-6 my-4 space-y-2 text-[var(--grey92)]">
//                             {children}
//                         </ol>
//                     ),

//                     li: ({ children }) => <li>{children}</li>,

//                     // Paragraphs
//                     p: ({ children }) => <p className="my-4 leading-relaxed text-[var(--grey92)]">{children}</p>,

//                     // Strong & Emphasis
//                     strong: ({ children }) => <strong className="font-semibold text-[var(--light)]">{children}</strong>,
//                     em: ({ children }) => <em className="italic text-[var(--grey99)]">{children}</em>,

//                     // Blockquote (used sometimes in policy text)
//                     blockquote: ({ children }) => (
//                         <blockquote className="border-s-4 border-[var(--primary)] ps-4 my-5 italic text-[var(--grey99)]">
//                             {children}
//                         </blockquote>
//                     ),

//                 }}
//             >
//                 {processedMarkdown}
//             </ReactMarkdown>
//         </div>
//     );
// };

// export default CustomMarkdownRenderer;

'use client';
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeSanitize from 'rehype-sanitize';      // always include for safety
import rehypeRaw from 'rehype-raw';                // optional – only enable when needed
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'; // ← added light theme

interface CustomMarkdownRendererProps {
    markdown: string;
    allowRawHtml?: boolean;       // default = false (safer)
    className?: string;
    // You can pass theme explicitly if you want – but usually better to use CSS variables
    forceTheme?: 'light' | 'dark';
    textAlign?: 'left' | 'center' | 'right';
}

const CustomMarkdownRenderer: React.FC<CustomMarkdownRendererProps> = ({
    markdown,
    allowRawHtml = false,
    className = '',
    forceTheme,
    textAlign = 'left',
}) => {
    // Simple preprocess to clean up your specific garbage patterns
    // const preprocess = (raw: string): string => {
    //     let text = raw;

    //     // Replace known artifacts from your sample data
    //     text = text?.replace(/GLYPH<c=0,font=\/BAAAAA\+OpenSans-Regular>/g, '→ ');
    //     text = text?.replace(/&amp;/g, '&');

    //     // Turn "Section: X.Y ..." into proper markdown headers
    //     text = text?.replace(
    //         /(Section:\s*\d+\.\s*[A-Za-z &()/]+(\s*\([^)]+\))?)/g,
    //         '\n\n### $1\n'
    //     );

    //     // Convert numbered steps to markdown list items
    //     text = text?.replace(/^(\d+\.\s+)/gm, '- $1');

    //     // Normalize bullet points
    //     text = text?.replace(/^\s*-\s*/gm, '- ');

    //     // Ensure bold text gets breathing room
    //     text = text?.replace(/\*\*(.*?)\*\*/g, '\n\n**$1**\n');

    //     return text.trim();
    // };
    const preprocess = (raw: string): string => {
        if (!raw) return '';

        return raw
            // 1. Remove known garbage
            .replace(/GLYPH<[^>]+>/g, '→ ')
            .replace(/&amp;/g, '&')

            // 2. Collapse multiple blank lines → max 2
            .replace(/\n{3,}/g, '\n\n')

            // 3. Remove empty list lines (very common bug)
            .replace(/^\s*[-*]\s*$/gm, '')                    // lone bullet
            .replace(/^\s*\d+\.\s*$/gm, '')                   // lone number

            // 4. Fix broken bold/italic across lines (common AI mistake)
            .replace(/\*\*([^\n*]+?)\*\*\s*\n\s*(?=[^*])/g, '**$1** ')

            // 5. Optional: force section-like lines to become headers
            // (only if you consistently see this pattern)
            .replace(/^(Section:\s*\d+\..*)$/gm, '\n### $1\n')

            .trim();
    };
    const processedMarkdown = preprocess(markdown);

    // Decide which syntax highlighter theme to use
    const isDark = forceTheme === 'dark' || (!forceTheme && document.documentElement.getAttribute('data-theme') !== 'light');
    const syntaxTheme = isDark ? oneDark : oneLight;

    return (
        <div className={` ${textAlign === "left" ? "text-left dir-ltr" : textAlign === "center" ? "text-center" : "text-right dir-rtl"} ${className}`}>
            <ReactMarkdown
                remarkPlugins={[remarkGfm]}
                rehypePlugins={allowRawHtml ? [rehypeRaw, rehypeSanitize] : [rehypeSanitize]}
                components={{
                    // ────────────────────────────────────────────────────────────────
                    // Code blocks (multi-line)
                    code({ node, inline, className, children, ...props }: any) {
                        const match = /language-(\w+)/.exec(className || '');
                        if (!inline && match) {
                            return (
                                <SyntaxHighlighter
                                    style={syntaxTheme}
                                    language={match[1]}
                                    PreTag="div"
                                    // dir={textAlign === 'right' ? 'rtl' : 'ltr'}
                                    customStyle={{
                                        margin: '1.25rem 0',
                                        borderRadius: '0.5rem',
                                        fontSize: '0.94rem',
                                        backgroundColor: 'var(--secondary25)',
                                    }}
                                    {...props}
                                >
                                    {String(children).replace(/\n$/, '')}
                                </SyntaxHighlighter>
                            );
                        }

                        // Inline code (e.g. `COMPLIANT`, `PARTIAL`, variable names)
                        const text = String(children).trim();

                        let textColor = 'var(--grey92)';
                        let bgColor = 'var(--secondary25)';

                        if (text?.includes('COMPLIANT')) {
                            textColor = 'var(--primary)';           // green-ish from your theme
                            bgColor = 'color-mix(in srgb, var(--primary) 15%, transparent)';
                        } else if (text?.includes('PARTIAL')) {
                            textColor = 'var(--primary-c5)';        // lighter green/teal from your theme
                            bgColor = 'color-mix(in srgb, var(--primary-c5) 20%, transparent)';
                        } else if (text?.includes('NON-COMPLIANT') || text?.includes('GAP')) {
                            textColor = 'var(--red)';               // your defined red
                            bgColor = 'color-mix(in srgb, var(--red) 20%, transparent)';
                        } else {
                            // fallback for other inline code
                            textColor = 'var(--primary-c1)';
                            bgColor = 'var(--secondary25)';
                        }
                        return (
                            <code
                                className={`font-medium px-1.5 py-0.5 rounded `}
                                // dir={textAlign === 'right' ? 'rtl' : 'ltr'}

                                {...props}

                            >
                                {text}
                            </code>
                        );
                    },

                    // Headings – use project colors
                    h1: ({ children }) => (
                        <h1 className="text-2xl sm:text-3xl font-bold mt-10 mb-5 border-b border-[var(--grey32)] pb-2.5 text-[var(--light)] ">
                            {children}
                        </h1>
                    ),
                    h2: ({ children }) => (
                        <h2 className="text-xl sm:text-2xl font-semibold mt-8 mb-4 text-[var(--primary)] ">
                            {children}
                        </h2>
                    ),
                    h3: ({ children }) => (
                        <h3 className="text-lg sm:text-xl font-medium mt-7 mb-3 text-[var(--grey99)] ">
                            {children}
                        </h3>
                    ),


                    hr: () => <hr className="my-8 border-[var(--grey32)]" />,

                    // Tables
                    table: ({ children }) => (
                        <div className="overflow-x-auto my-6 rounded-lg border border-[var(--grey32)]">
                            <table className="min-w-full border-collapse">{children}</table>
                        </div>
                    ),
                    th: ({ children }) => (
                        <th className="border border-[var(--grey32)] bg-[var(--secondary25)] px-4 py-2.5 text-start font-semibold text-[var(--grey99)]">
                            {children}
                        </th>
                    ),
                    td: ({ children }) => (
                        <td className="border border-[var(--grey32)] px-4 py-2.5 text-start text-[var(--grey92)]">
                            {children}
                        </td>
                    ),


                    // Lists
                    ul: ({ children }) => (
                        <ul className={`list-disc ps-6 my-4 space-y-2 text-[var(--grey92)] ${textAlign === 'right' ? 'content-right list-none' : 'content-left list-none'}`}>
                            {children}
                        </ul>
                    ),
                    ol: ({ children }) => (
                        <ol className="list-decimal ps-6 my-4 space-y-2 text-[var(--grey92)]">
                            {children}
                        </ol>
                    ),

                    li: ({ children }) => <li>{children}</li>,

                    // Paragraphs
                    p: ({ children }) => <p className="my-4 leading-relaxed text-[var(--grey92)] ">{children}</p>,

                    // Strong & Emphasis
                    strong: ({ children }) => <strong className="font-semibold text-[var(--light)]">{children}</strong>,
                    em: ({ children }) => <em className="italic text-[var(--grey99)]">{children}</em>,

                    // Blockquote (used sometimes in policy text)
                    blockquote: ({ children }) => (
                        <blockquote className="border-s-4 border-[var(--primary)] ps-4 my-5 italic text-[var(--grey99)]">
                            {children}
                        </blockquote>
                    ),

                }}
            >
                {processedMarkdown}
            </ReactMarkdown>
        </div>
    );
};

export default CustomMarkdownRenderer;