"use client";

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

interface MarkdownContentProps {
  children: string;
  /** Applied to the outer wrapper div — use for text size / color overrides */
  className?: string;
}

/**
 * Renders LLM-generated markdown as styled HTML.
 *
 * Rules:
 *  - No raw HTML passthrough — only standard markdown elements
 *  - Headings use compact sizing (h2=15px, h3=13px) so they read as
 *    section labels, not blog-post headlines
 *  - Text color/size are inherited from the wrapper div via `className`
 *    so each surface can tune density without duplicating renderers
 *  - Links open in new tab with noopener
 *  - Code blocks get a subtle mono box; inline code gets an inline pill
 */
export function MarkdownContent({ children, className }: MarkdownContentProps) {
  if (!children) return null;
  return (
    <div className={className}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          // Headings — compact scale, not blog-post size
          h1: ({ children }) => (
            <p className="text-base font-bold text-slate-900 mt-3 mb-1 first:mt-0 last:mb-0">
              {children}
            </p>
          ),
          h2: ({ children }) => (
            <p className="text-[0.9375rem] font-semibold text-slate-800 mt-2.5 mb-1 first:mt-0 last:mb-0">
              {children}
            </p>
          ),
          h3: ({ children }) => (
            <p className="text-[0.8125rem] font-semibold text-slate-800 mt-2 mb-0.5 first:mt-0 last:mb-0">
              {children}
            </p>
          ),
          h4: ({ children }) => (
            <p className="text-xs font-semibold text-slate-700 mt-1.5 mb-0.5 uppercase tracking-wide first:mt-0 last:mb-0">
              {children}
            </p>
          ),
          // Paragraphs — inherit text size/color from wrapper className
          p: ({ children }) => (
            <p className="leading-relaxed mb-1.5 last:mb-0">{children}</p>
          ),
          strong: ({ children }) => (
            <strong className="font-semibold text-slate-900">{children}</strong>
          ),
          em: ({ children }) => <em className="italic">{children}</em>,
          ul: ({ children }) => (
            <ul className="list-disc list-outside pl-4 space-y-0.5 my-1.5">
              {children}
            </ul>
          ),
          ol: ({ children }) => (
            <ol className="list-decimal list-outside pl-4 space-y-0.5 my-1.5">
              {children}
            </ol>
          ),
          li: ({ children }) => (
            <li className="leading-relaxed">{children}</li>
          ),
          a: ({ href, children }) => (
            <a
              href={href ?? "#"}
              target="_blank"
              rel="noopener noreferrer"
              className="text-brand-600 underline hover:text-brand-700 underline-offset-2"
            >
              {children}
            </a>
          ),
          // Block code container
          pre: ({ children }) => (
            <pre className="text-[11px] font-mono bg-slate-50 border border-slate-100 rounded-md p-3 overflow-x-auto my-2 whitespace-pre-wrap break-words">
              {children}
            </pre>
          ),
          // Inline code (no language class) vs fenced code (has language class)
          code: ({ className: codeClass, children }) =>
            codeClass ? (
              // Inside a fenced code block — pre handles the container
              <code className={codeClass}>{children}</code>
            ) : (
              <code className="text-[11px] font-mono bg-slate-100 text-slate-700 px-1 py-0.5 rounded">
                {children}
              </code>
            ),
          blockquote: ({ children }) => (
            <blockquote className="border-l-2 border-slate-200 pl-3 my-2 text-slate-500 italic">
              {children}
            </blockquote>
          ),
          hr: () => <hr className="border-slate-200 my-3" />,
        }}
      >
        {children}
      </ReactMarkdown>
    </div>
  );
}

/**
 * Strips markdown syntax to produce clean plain text.
 * Use for truncated / line-clamp preview contexts where markdown
 * block elements would break the clamp layout.
 */
export function stripMarkdown(text: string): string {
  return text
    .replace(/#{1,6}\s+/g, "")
    .replace(/\*\*(.+?)\*\*/g, "$1")
    .replace(/\*(.+?)\*/g, "$1")
    .replace(/`(.+?)`/g, "$1")
    .replace(/^\s*[-*+]\s+/gm, "")
    .replace(/^\s*\d+\.\s+/gm, "")
    .replace(/\[(.+?)\]\(.+?\)/g, "$1")
    .replace(/\n+/g, " ")
    .trim();
}
