"use client";

/**
 * Renders markdown-formatted content with proper H1/H2/H3 styling.
 * Only handles headings + paragraphs — not full markdown. Lightweight
 * and dependency-free. Shows a heading count indicator at the bottom.
 */

import React from "react";

interface Props {
  content: string;
  className?: string;
}

function parseLine(line: string): React.ReactElement | null {
  const trimmed = line.trim();
  if (!trimmed) return null;

  if (trimmed.startsWith("### ")) {
    return <h3 className="text-lg font-semibold text-slate-900 mt-5 mb-2">{trimmed.slice(4)}</h3>;
  }
  if (trimmed.startsWith("## ")) {
    return <h2 className="text-xl font-bold text-slate-900 mt-8 mb-3 pt-4 border-t border-slate-100">{trimmed.slice(3)}</h2>;
  }
  if (trimmed.startsWith("# ")) {
    return <h1 className="text-2xl font-bold text-slate-900 mb-4">{trimmed.slice(2)}</h1>;
  }
  if (trimmed.startsWith("- ") || trimmed.startsWith("* ")) {
    return <li className="text-sm text-slate-700 leading-relaxed ml-4 list-disc">{trimmed.slice(2)}</li>;
  }
  return <p className="text-sm text-slate-700 leading-relaxed mb-3">{trimmed}</p>;
}

export default function MarkdownRenderer({ content, className }: Props) {
  const lines = content.split("\n");
  const elements: React.ReactElement[] = [];

  lines.forEach((line, i) => {
    const el = parseLine(line);
    if (el) elements.push(React.cloneElement(el, { key: i }));
  });

  // Count headings
  const h1Count = lines.filter((l) => /^# [^#]/.test(l.trim())).length;
  const h2Count = lines.filter((l) => /^## [^#]/.test(l.trim())).length;
  const h3Count = lines.filter((l) => /^### /.test(l.trim())).length;

  return (
    <div className={className}>
      <div className="prose-sm max-w-none">{elements}</div>
      {(h1Count > 0 || h2Count > 0 || h3Count > 0) && (
        <div className="mt-4 pt-3 border-t border-slate-100 flex items-center gap-3">
          <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Headings</span>
          <span className="text-[11px] font-semibold text-slate-600">H1: {h1Count}</span>
          <span className="text-[11px] font-semibold text-slate-600">H2: {h2Count}</span>
          <span className="text-[11px] font-semibold text-slate-600">H3: {h3Count}</span>
        </div>
      )}
    </div>
  );
}

/** Convert BriefSection[] to markdown string for rendering + copy */
export function sectionsToMarkdown(sections: Array<{ type: string; heading?: string; label?: string; content?: string }>): string {
  return sections.map((s) => {
    const prefix =
      s.type === "h1" || s.type === "title" ? "# " :
      s.type === "h2" || s.type === "question" ? "## " :
      s.type === "h3" ? "### " :
      s.type === "meta_title" ? "# " :
      s.type === "faq" ? "## " : "";
    const headingText = s.heading || s.label;
    const content = s.content || "";
    const heading = headingText ? `${prefix}${headingText}\n` : (prefix ? `${prefix}${content.split("\n")[0]}\n` : "");

    if (s.type === "faq") {
      try {
        const items = JSON.parse(content) as Array<{ q: string; a: string }>;
        return `${heading}${items.map((f) => `### ${f.q}\n${f.a}`).join("\n\n")}`;
      } catch { return `${heading}${content}`; }
    }

    return heading ? `${heading}${content}` : content;
  }).join("\n\n");
}
