import Link from "next/link";
import type { ReactNode } from "react";

/** Tiny, safe markdown subset for admin-edited pages: ## / ### headings, paragraphs, "- " lists, **bold**, [links](/path). No raw HTML. */
function inline(text: string, keyBase: string): ReactNode[] {
  const out: ReactNode[] = [];
  const re = /(\*\*[^*]+\*\*|\[[^\]]+\]\([^)\s]+\))/g;
  let last = 0, m: RegExpExecArray | null, i = 0;
  while ((m = re.exec(text))) {
    if (m.index > last) out.push(text.slice(last, m.index));
    const tok = m[0];
    if (tok.startsWith("**")) out.push(<strong key={`${keyBase}-${i++}`} className="font-medium">{tok.slice(2, -2)}</strong>);
    else {
      const [, label, href] = tok.match(/\[([^\]]+)\]\(([^)]+)\)/)!;
      const safe = /^(\/|https?:\/\/|mailto:|tel:)/.test(href) ? href : "#";
      out.push(safe.startsWith("/") ? <Link key={`${keyBase}-${i++}`} href={safe} className="underline underline-offset-4">{label}</Link> : <a key={`${keyBase}-${i++}`} href={safe} className="underline underline-offset-4" rel="noopener noreferrer">{label}</a>);
    }
    last = m.index + tok.length;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

export function Markdown({ source, className = "" }: { source: string; className?: string }) {
  const blocks = source.replace(/\r/g, "").split(/\n{2,}/);
  return (
    <div className={`prose-veloura ${className}`}>
      {blocks.map((b, i) => {
        const t = b.trim();
        if (!t) return null;
        if (t.startsWith("### ")) return <h3 key={i}>{inline(t.slice(4), `h${i}`)}</h3>;
        if (t.startsWith("## ")) return <h2 key={i}>{inline(t.slice(3), `h${i}`)}</h2>;
        if (t.split("\n").every((l) => l.startsWith("- ")))
          return <ul key={i}>{t.split("\n").map((l, j) => <li key={j}>{inline(l.slice(2), `l${i}${j}`)}</li>)}</ul>;
        return <p key={i}>{t.split("\n").flatMap((l, j) => (j ? [<br key={`br${j}`} />, ...inline(l, `p${i}${j}`)] : inline(l, `p${i}${j}`)))}</p>;
      })}
    </div>
  );
}
