'use client'; import Link from 'next/link'; import { Fragment, type ReactNode } from 'react'; /** * Tiny dependency-free markdown renderer for assistant answers: paragraphs, headings, bullet and * numbered lists, pipe tables, bold/italic/code and links (internal links use next/link). * Not a full CommonMark implementation — enough for terminal-style research answers. */ export function Markdown({ text }: { text: string }) { const blocks = splitBlocks(text); return
{blocks.map((b, i) => {renderBlock(b)})}
; } function splitBlocks(text: string): string[] { return text.replace(/\r\n/g, '\n').split(/\n{2,}/).map((b) => b.trim()).filter(Boolean); } function renderBlock(block: string): ReactNode { const lines = block.split('\n'); if (lines.length >= 2 && lines.every((l) => l.trim().startsWith('|'))) return renderTable(lines); if (lines.every((l) => /^\s*[-*•]\s+/.test(l))) return ; if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) return
    {lines.map((l, i) =>
  1. {inline(l.replace(/^\s*\d+[.)]\s+/, ''))}
  2. )}
; const h = block.match(/^(#{1,4})\s+(.*)$/); if (h && lines.length === 1) { const level = h[1]!.length; const cls = level <= 2 ? 'text-sm font-semibold' : 'text-[13px] font-semibold'; return

{inline(h[2]!)}

; } if (block.startsWith('```')) return
{block.replace(/^```\w*\n?/, '').replace(/```$/, '')}
; return

{lines.map((l, i) => {i > 0 ?
: null}{inline(l)}
)}

; } function renderTable(lines: string[]): ReactNode { const rows = lines.filter((l) => !/^\s*\|?\s*:?-{2,}/.test(l)).map((l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim())); const [head, ...body] = rows; if (!head) return null; return (
{head.map((c, i) => )} {body.map((r, i) => ( {r.map((c, j) => )} ))}
{inline(c)}
{inline(c)}
); } const INLINE = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g; function inline(s: string): ReactNode { const parts = s.split(INLINE).filter((p) => p !== ''); return parts.map((p, i) => { if (p.startsWith('**') && p.endsWith('**')) return {p.slice(2, -2)}; if (p.startsWith('*') && p.endsWith('*') && p.length > 2) return {p.slice(1, -1)}; if (p.startsWith('`') && p.endsWith('`')) return {p.slice(1, -1)}; const m = p.match(/^\[([^\]]+)\]\(([^)]+)\)$/); if (m) { const href = m[2]!; const cls = 'font-medium underline decoration-border-strong underline-offset-2 hover:decoration-fg'; return href.startsWith('/') ? {m[1]} : {m[1]}; } return {p}; }); }