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

const PLUGINS = [remarkGfm];

const COMPONENTS = {
  p: ({ children }) => <p className="mb-3 last:mb-0">{children}</p>,
  strong: ({ children }) => <strong className="font-semibold text-[var(--color-text)]">{children}</strong>,
  em: ({ children }) => <em className="italic">{children}</em>,
  h1: ({ children }) => <h1 className="text-xl font-bold mb-2 mt-4">{children}</h1>,
  h2: ({ children }) => <h2 className="text-lg font-bold mb-2 mt-3">{children}</h2>,
  h3: ({ children }) => <h3 className="text-base font-bold mb-1 mt-2">{children}</h3>,
  ul: ({ children }) => <ul className="list-disc pl-5 mb-3 space-y-1">{children}</ul>,
  ol: ({ children }) => <ol className="list-decimal pl-5 mb-3 space-y-1">{children}</ol>,
  li: ({ children }) => <li className="leading-relaxed">{children}</li>,
  a: ({ href, children }) => (
    <a href={href} target="_blank" rel="noopener noreferrer" className="text-[var(--color-blue)] hover:underline">
      {children}
    </a>
  ),
  blockquote: ({ children }) => (
    <blockquote className="border-l-2 border-[var(--color-blue)]/40 pl-3 my-2 text-[var(--color-text-secondary)]">
      {children}
    </blockquote>
  ),
  code: ({ inline, className, children }) => {
    if (inline) {
      return (
        <code className="px-1.5 py-0.5 bg-[var(--color-surface-high)] rounded text-[13px] font-mono text-[var(--color-blue)]">
          {children}
        </code>
      );
    }
    const lang = className?.replace("language-", "") || "";
    return (
      <div className="my-3 rounded-xl overflow-hidden border border-[var(--color-outline)]">
        {lang && (
          <div className="px-3 py-1.5 bg-[var(--color-surface-high)] text-[10px] font-mono text-[var(--color-text-secondary)] uppercase tracking-wider border-b border-[var(--color-outline)]">
            {lang}
          </div>
        )}
        <pre className="p-3 bg-[var(--color-surface)] overflow-x-auto">
          <code className="text-[13px] font-mono leading-relaxed text-[var(--color-text)]">
            {children}
          </code>
        </pre>
      </div>
    );
  },
  table: ({ children }) => (
    <div className="my-3 overflow-x-auto">
      <table className="w-full text-sm border-collapse">{children}</table>
    </div>
  ),
  th: ({ children }) => (
    <th className="text-left px-3 py-2 bg-[var(--color-surface)] border border-[var(--color-outline)] font-medium">
      {children}
    </th>
  ),
  td: ({ children }) => (
    <td className="px-3 py-2 border border-[var(--color-outline)]">{children}</td>
  ),
  hr: () => <hr className="my-4 border-[var(--color-outline)]" />,
};

export default function Markdown({ children }) {
  return (
    <ReactMarkdown remarkPlugins={PLUGINS} components={COMPONENTS}>
      {children}
    </ReactMarkdown>
  );
}
