"use client";

import * as React from "react";

/** Tiny markdown: **bold**, _italic_, `code`, and "- " bullets. */
export function SoftMarkdown({ text, className }: { text: string; className?: string }) {
  const blocks = text.split("\n");

  return (
    <div className={className}>
      {blocks.map((line, index) => {
        if (line.trim() === "") {
          return <div key={index} className="h-2" />;
        }
        if (line.startsWith("- ")) {
          return (
            <div key={index} className="flex gap-2">
              <span className="shrink-0 text-muted-foreground">•</span>
              <span>{renderInline(line.slice(2))}</span>
            </div>
          );
        }
        return (
          <p key={index} className="leading-relaxed">
            {renderInline(line)}
          </p>
        );
      })}
    </div>
  );
}

function renderInline(line: string): React.ReactNode[] {
  const nodes: React.ReactNode[] = [];
  const pattern = /(\*\*[^*]+\*\*|_[^_]+_|`[^`]+`)/g;
  let last = 0;
  let match: RegExpExecArray | null;
  let key = 0;

  while ((match = pattern.exec(line)) !== null) {
    if (match.index > last) {
      nodes.push(line.slice(last, match.index));
    }
    const token = match[0];
    if (token.startsWith("**") && token.endsWith("**")) {
      nodes.push(
        <strong key={key++} className="font-semibold">
          {token.slice(2, -2)}
        </strong>,
      );
    } else if (token.startsWith("_") && token.endsWith("_")) {
      nodes.push(
        <em key={key++} className="text-muted-foreground italic">
          {token.slice(1, -1)}
        </em>,
      );
    } else if (token.startsWith("`") && token.endsWith("`")) {
      nodes.push(
        <code key={key++} className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">
          {token.slice(1, -1)}
        </code>,
      );
    } else {
      nodes.push(token);
    }
    last = match.index + token.length;
  }

  if (last < line.length) {
    nodes.push(line.slice(last));
  }

  return nodes;
}
