/**
 * MarkdownText — renders a markdown string as styled HTML.
 *
 * Features:
 * - react-markdown + remark-gfm (tables, strikethrough, etc.)
 * - External links open in a new tab.
 * - MITRE (Citation: ...) patterns are extracted from the body text,
 *   replaced with superscript numbers ¹²³, and shown as a compact
 *   collapsible "Sources" section below.
 *
 * Usage:
 *   <MarkdownText content={technique.description} />
 *   <MarkdownText content={test.red_summary} className="text-sm text-gray-400" />
 */

import { useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Components } from "react-markdown";
import { ChevronDown, ChevronUp, BookOpen } from "lucide-react";

/* ── Citation pre-processing ──────────────────────────────────────── */

const CITATION_RE = /\s*\(Citation:\s*([^)]+)\)/g;

const SUPERSCRIPTS = "⁰¹²³⁴⁵⁶⁷⁸⁹";

function toSuperscript(n: number): string {
  return String(n)
    .split("")
    .map((d) => SUPERSCRIPTS[parseInt(d)] ?? d)
    .join("");
}

interface ProcessedContent {
  /** Text with (Citation: …) replaced by ¹²³ superscript numbers */
  text: string;
  /** Ordered list of unique citation strings */
  citations: string[];
}

function processCitations(raw: string): ProcessedContent {
  const citations: string[] = [];

  const text = raw.replace(CITATION_RE, (_, cite: string) => {
    const trimmed = cite.trim();
    let idx = citations.indexOf(trimmed);
    if (idx === -1) {
      citations.push(trimmed);
      idx = citations.length - 1;
    }
    return toSuperscript(idx + 1);
  });

  return { text: text.trim(), citations };
}

/* ── ReactMarkdown component overrides ───────────────────────────── */

const mdComponents: Components = {
  a: ({ href, children, ...props }) => (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      className="text-cyan-400 underline underline-offset-2 hover:text-cyan-300 transition-colors"
      {...props}
    >
      {children}
    </a>
  ),
  p: ({ children }) => (
    <p className="mb-2 last:mb-0 leading-relaxed">{children}</p>
  ),
  strong: ({ children }) => (
    <strong className="font-semibold text-gray-100">{children}</strong>
  ),
  em: ({ children }) => <em className="italic text-gray-300">{children}</em>,
  code: ({ children, className }) => {
    const isBlock = className?.startsWith("language-");
    if (isBlock) {
      return (
        <code className="block rounded-md bg-gray-800 px-3 py-2 font-mono text-xs text-gray-200 whitespace-pre-wrap">
          {children}
        </code>
      );
    }
    return (
      <code className="rounded bg-gray-800 px-1 py-0.5 font-mono text-xs text-cyan-300">
        {children}
      </code>
    );
  },
  pre: ({ children }) => (
    <pre className="my-2 overflow-x-auto rounded-md bg-gray-800 p-3 text-xs">
      {children}
    </pre>
  ),
  ul: ({ children }) => (
    <ul className="mb-2 list-disc pl-5 space-y-0.5">{children}</ul>
  ),
  ol: ({ children }) => (
    <ol className="mb-2 list-decimal pl-5 space-y-0.5">{children}</ol>
  ),
  li: ({ children }) => <li className="leading-relaxed">{children}</li>,
  h1: ({ children }) => (
    <h1 className="mb-2 text-base font-semibold text-white">{children}</h1>
  ),
  h2: ({ children }) => (
    <h2 className="mb-1.5 text-sm font-semibold text-white">{children}</h2>
  ),
  h3: ({ children }) => (
    <h3 className="mb-1 text-sm font-medium text-gray-200">{children}</h3>
  ),
  blockquote: ({ children }) => (
    <blockquote className="my-2 border-l-2 border-cyan-500/40 pl-3 text-gray-400 italic">
      {children}
    </blockquote>
  ),
  hr: () => <hr className="my-3 border-gray-700" />,
};

/* ── Citations footer sub-component ─────────────────────────────── */

function CitationsFooter({ citations }: { citations: string[] }) {
  // Auto-expand if few citations; collapse for many
  const [open, setOpen] = useState(citations.length <= 3);

  return (
    <div className="mt-3 border-t border-gray-800 pt-2">
      <button
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1.5 text-[11px] text-gray-500 hover:text-gray-400 transition-colors select-none"
      >
        <BookOpen className="h-3 w-3" />
        <span>
          {citations.length} source{citations.length !== 1 ? "s" : ""}
        </span>
        {open ? (
          <ChevronUp className="h-3 w-3" />
        ) : (
          <ChevronDown className="h-3 w-3" />
        )}
      </button>

      {open && (
        <ol className="mt-1.5 space-y-0.5 list-none">
          {citations.map((cite, i) => (
            <li key={i} className="flex items-baseline gap-1.5 text-[11px] text-gray-500">
              <span className="shrink-0 text-gray-600 select-none">
                {toSuperscript(i + 1)}
              </span>
              <span className="font-mono">{cite}</span>
            </li>
          ))}
        </ol>
      )}
    </div>
  );
}

/* ── Main component ──────────────────────────────────────────────── */

interface MarkdownTextProps {
  content: string | null | undefined;
  /** Extra classes on the wrapper div */
  className?: string;
}

export default function MarkdownText({ content, className }: MarkdownTextProps) {
  if (!content) return null;

  const { text, citations } = processCitations(content);

  return (
    <div className={className}>
      <ReactMarkdown remarkPlugins={[remarkGfm]} components={mdComponents}>
        {text}
      </ReactMarkdown>
      {citations.length > 0 && <CitationsFooter citations={citations} />}
    </div>
  );
}
