import Link from "next/link";
import Markdown from "react-markdown";
import type { LearnVariant } from "@/lib/content/zhouyi";

function resolveLearnHref(
  href: string | undefined,
  variant: LearnVariant,
): string | undefined {
  if (!href) {
    return href;
  }
  if (href.startsWith("http://") || href.startsWith("https://")) {
    return href;
  }

  const base = variant === "traditional" ? "/learn" : "/learn/other";

  if (href === "index.md" || href === "./index.md") {
    return base;
  }
  if (href === "other/index.md") {
    return "/learn/other";
  }
  if (href.endsWith("/index.md")) {
    const mark = href.replace(/\/index\.md$/, "").replace(/^\.\//, "");
    if (mark.startsWith("other/")) {
      return `/learn/other/${mark.slice("other/".length)}`;
    }
    return `${base}/${mark}`;
  }
  return href;
}

export default function MarkdownContent({
  content,
  variant = "traditional",
}: {
  content: string;
  variant?: LearnVariant;
}) {
  return (
    <Markdown
      className="prose max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-a:text-primary"
      components={{
        a: ({ href, children, ...props }) => {
          const resolved = resolveLearnHref(href, variant);
          if (resolved?.startsWith("/")) {
            return (
              <Link href={resolved} {...props}>
                {children}
              </Link>
            );
          }
          return (
            <a href={resolved} {...props}>
              {children}
            </a>
          );
        },
        img: ({ src, alt, ...props }) => {
          if (typeof src === "string" && !src.startsWith("http")) {
            return (
              <span className="my-2 block rounded border border-dashed p-4 text-center text-sm text-muted-foreground">
                [{alt || "卦象图片"}]
              </span>
            );
          }
          return <img src={src} alt={alt} {...props} />;
        },
      }}
    >
      {content}
    </Markdown>
  );
}
