import type { ReactNode } from "react";

type BlogBodyRendererProps = {
  blocks: string[];
  size?: "sm" | "base";
};

function renderInlineText(text: string) {
  const parts = text.split(/(\*\*[^*]+\*\*|_[^_]+_)/g).filter(Boolean);

  return parts.map((part, index): ReactNode => {
    const key = `${index}-${part}`;

    if (part.startsWith("**") && part.endsWith("**")) {
      return (
        <strong key={key} className="font-black text-foreground">
          {part.slice(2, -2)}
        </strong>
      );
    }

    if (part.startsWith("_") && part.endsWith("_")) {
      return (
        <em key={key} className="italic text-foreground/90">
          {part.slice(1, -1)}
        </em>
      );
    }

    return part;
  });
}

export function BlogBodyRenderer({ blocks, size = "base" }: BlogBodyRendererProps) {
  const textClass = size === "sm" ? "text-sm leading-7" : "text-base leading-8";
  const headingClass =
    size === "sm"
      ? "text-lg font-black tracking-tight text-foreground"
      : "text-2xl font-black tracking-tight text-foreground";
  const elements: ReactNode[] = [];
  let listItems: string[] = [];

  function flushList() {
    if (listItems.length === 0) {
      return;
    }

    const listKey = `list-${elements.length}`;

    elements.push(
      <ul key={listKey} className={`list-disc space-y-2 pl-5 ${textClass} text-muted-foreground`}>
        {listItems.map((item) => (
          <li key={item}>{renderInlineText(item)}</li>
        ))}
      </ul>,
    );
    listItems = [];
  }

  blocks
    .map((block) => block.trim())
    .filter(Boolean)
    .forEach((block) => {
      if (block.startsWith("- ")) {
        listItems.push(block.replace(/^-\s+/, ""));
        return;
      }

      flushList();

      if (block.startsWith("## ")) {
        elements.push(
          <h3 key={block} className={headingClass}>
            {renderInlineText(block.replace(/^##\s+/, ""))}
          </h3>,
        );
        return;
      }

      elements.push(
        <p key={block} className={`${textClass} text-muted-foreground`}>
          {renderInlineText(block)}
        </p>,
      );
    });

  flushList();

  return <div className="space-y-4">{elements}</div>;
}
