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

const TOKEN = /(\*\*[^*]+\*\*|\[[^\]]+\]\([^)\s]+\))/g;
const LINK = /^\[([^\]]+)\]\(([^)\s]+)\)$/;

/**
 * Renders the two inline marks the content model allows: **bold** and [label](href).
 * Internal hrefs use next/link; external hrefs open normally with safe rel attributes.
 */
export function renderInline(text: string, linkClassName = "link-underline font-medium"): ReactNode {
  const parts = text.split(TOKEN).filter((part) => part !== "");
  return parts.map((part, index) => {
    if (part.startsWith("**") && part.endsWith("**")) {
      return (
        <strong key={index} className="font-semibold">
          {part.slice(2, -2)}
        </strong>
      );
    }
    const link = part.match(LINK);
    if (link) {
      const [, label, href] = link;
      if (href.startsWith("/")) {
        return (
          <Link key={index} href={href} className={linkClassName}>
            {label}
          </Link>
        );
      }
      return (
        <a key={index} href={href} className={linkClassName} rel="noopener noreferrer" target="_blank">
          {label}
        </a>
      );
    }
    return <Fragment key={index}>{part}</Fragment>;
  });
}
