/**
 * WorthDoing.ai
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File: src/components/wd/Markdown.tsx
 * Description: Sanitized markdown renderer for opportunity reports, with [n] citations linked to evidence.
 */
"use client";

import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { ReactNode } from "react";

/** Turn bare [n] citation markers inside text nodes into anchor links to #evidence-n. */
function linkCitations(children: ReactNode): ReactNode {
  const walk = (node: ReactNode, key = 0): ReactNode => {
    if (typeof node === "string") {
      const parts = node.split(/(\[\d{1,3}\])/g);
      if (parts.length === 1) return node;
      return parts.map((part, i) => {
        const m = part.match(/^\[(\d{1,3})\]$/);
        if (!m) return part;
        return (
          <a
            key={`${key}-${i}`}
            href={`#evidence-${m[1]}`}
            className="mx-0.5 rounded bg-verdict/10 px-1 py-0.5 font-mono text-[11px] font-medium text-verdict no-underline hover:bg-verdict/20"
          >
            {m[1]}
          </a>
        );
      });
    }
    if (Array.isArray(node)) return node.map((n, i) => walk(n, i));
    return node;
  };
  return walk(children);
}

export function Markdown({ children }: { children: string }) {
  return (
    <div className="prose-wd">
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          h2: ({ children }) => (
            <h2 className="mb-3 mt-8 font-heading text-xl font-semibold text-ink first:mt-0">{children}</h2>
          ),
          h3: ({ children }) => (
            <h3 className="mb-2 mt-6 font-heading text-lg font-semibold text-ink">{children}</h3>
          ),
          p: ({ children }) => (
            <p className="mb-4 text-[15px] leading-relaxed text-ink/90">{linkCitations(children)}</p>
          ),
          li: ({ children }) => (
            <li className="mb-1.5 ml-4 list-disc text-[15px] leading-relaxed text-ink/90">
              {linkCitations(children)}
            </li>
          ),
          a: ({ href, children }) => (
            <a
              href={href}
              target="_blank"
              rel="noopener noreferrer"
              className="text-tele underline decoration-tele/40 underline-offset-2 hover:decoration-tele"
            >
              {children}
            </a>
          ),
          strong: ({ children }) => <strong className="font-semibold text-ink">{children}</strong>,
          blockquote: ({ children }) => (
            <blockquote className="mb-4 border-l-2 border-verdict/40 pl-4 italic text-ink-soft">
              {children}
            </blockquote>
          ),
          code: ({ children }) => (
            <code className="rounded bg-secondary px-1.5 py-0.5 font-mono text-[13px] text-ink">{children}</code>
          ),
          table: ({ children }) => (
            <div className="mb-4 overflow-x-auto">
              <table className="w-full border-collapse text-sm">{children}</table>
            </div>
          ),
          th: ({ children }) => (
            <th className="border-b border-line px-3 py-2 text-left font-medium text-ink">{children}</th>
          ),
          td: ({ children }) => (
            <td className="border-b border-line/60 px-3 py-2 text-ink/90">{linkCitations(children)}</td>
          ),
        }}
      >
        {children}
      </ReactMarkdown>
    </div>
  );
}
