import { Fragment, type ReactNode } from "react";

/**
 * Minimal, safe Markdown renderer for article bodies stored in MySQL.
 * Supports ##/### headings, paragraphs, "- " lists and **bold**. Everything is rendered as React text,
 * so content can never inject HTML or scripts.
 */

export type Heading = { id: string; text: string; level: 2 | 3 };
type Block =
  | { kind: "heading"; level: 2 | 3; text: string; id: string }
  | { kind: "list"; items: string[] }
  | { kind: "paragraph"; text: string };

const slugify = (text: string) =>
  text
    .toLowerCase()
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 80) || "section";

export const parseMarkdown = (source: string): Block[] => {
  const used = new Map<string, number>();
  const uniqueId = (text: string) => {
    const base = slugify(text);
    const count = used.get(base) ?? 0;
    used.set(base, count + 1);
    return count ? `${base}-${count + 1}` : base;
  };

  return source
    .split(/\n{2,}/)
    .map((chunk) => chunk.trim())
    .filter(Boolean)
    .map((chunk): Block => {
      const heading = /^(#{2,3})\s+(.+)$/.exec(chunk);
      if (heading) {
        const level = heading[1]!.length as 2 | 3;
        const text = heading[2]!.trim();
        return { kind: "heading", level, text, id: uniqueId(text) };
      }
      const lines = chunk.split("\n");
      if (lines.every((line) => /^-\s+/.test(line))) return { kind: "list", items: lines.map((line) => line.replace(/^-\s+/, "")) };
      return { kind: "paragraph", text: lines.join(" ") };
    });
};

export const extractHeadings = (blocks: Block[]): Heading[] =>
  blocks.flatMap((b) => (b.kind === "heading" ? [{ id: b.id, text: b.text, level: b.level }] : []));

const inline = (text: string): ReactNode =>
  text.split(/(\*\*[^*]+\*\*)/g).map((part, i) =>
    part.startsWith("**") && part.endsWith("**") ? <strong key={i}>{part.slice(2, -2)}</strong> : <Fragment key={i}>{part}</Fragment>,
  );

const isPlaceholder = (text: string) => /^\*{0,2}\[[^\]]+\]\*{0,2}$/.test(text.trim());

export function MarkdownBody({ blocks }: { blocks: Block[] }) {
  return (
    <div className="space-y-6 text-[1.08rem] leading-relaxed text-ink/85">
      {blocks.map((block, i) => {
        if (block.kind === "heading") {
          const Tag = block.level === 2 ? "h2" : "h3";
          return (
            <Tag key={i} id={block.id} className={`scroll-mt-28 font-serif text-ink ${block.level === 2 ? "pt-6 text-3xl md:text-4xl" : "pt-2 text-2xl"}`}>
              {block.text}
            </Tag>
          );
        }
        if (block.kind === "list") {
          return (
            <ul key={i} className="list-disc space-y-2 pl-6 marker:text-gold">
              {block.items.map((item, j) => (
                <li key={j}>{inline(item)}</li>
              ))}
            </ul>
          );
        }
        return (
          <p key={i} className={isPlaceholder(block.text) ? "text-sm tracking-[0.12em] text-gold-ink" : undefined}>
            {inline(block.text)}
          </p>
        );
      })}
    </div>
  );
}
