import Image from "next/image";
import type { ReactNode } from "react";
import type { MarkdownBlock } from "@/lib/library";

function renderInline(text: string): ReactNode[] {
  const tokens = text.split(/(\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g).filter(Boolean);
  return tokens.map((token, index) => {
    const strong = token.match(/^\*\*(.+)\*\*$/);
    if (strong) return <strong key={`${token}-${index}`}>{strong[1]}</strong>;
    const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
    if (link) return <a key={`${token}-${index}`} href={link[2]}>{link[1]}</a>;
    return token;
  });
}

export function MarkdownArticle({ blocks }: { blocks: MarkdownBlock[] }) {
  return (
    <div className="library-prose">
      {blocks.map((block, index) => {
        switch (block.type) {
          case "heading":
            return block.level === 2 ? (
              <h2 id={block.id} key={block.id}>{renderInline(block.text)}</h2>
            ) : (
              <h3 id={block.id} key={block.id}>{renderInline(block.text)}</h3>
            );
          case "paragraph":
            return <p key={`paragraph-${index}`}>{renderInline(block.text)}</p>;
          case "blockquote":
            return <blockquote key={`quote-${index}`}>{renderInline(block.text)}</blockquote>;
          case "list": {
            const List = block.ordered ? "ol" : "ul";
            return (
              <List key={`list-${index}`}>
                {block.items.map((item) => <li key={item}>{renderInline(item)}</li>)}
              </List>
            );
          }
          case "image":
            return (
              <figure key={`${block.src}-${index}`}>
                <Image src={block.src} alt={block.alt} width={1200} height={630} sizes="(max-width: 48rem) 100vw, 760px" />
              </figure>
            );
          case "table":
            return (
              <div className="library-table-scroll" key={`table-${index}`} tabIndex={0}>
                <table>
                  <thead><tr>{block.headers.map((header) => <th key={header}>{renderInline(header)}</th>)}</tr></thead>
                  <tbody>{block.rows.map((row, rowIndex) => <tr key={`row-${rowIndex}`}>{row.map((cell, cellIndex) => <td key={`${cell}-${cellIndex}`}>{renderInline(cell)}</td>)}</tr>)}</tbody>
                </table>
              </div>
            );
        }
      })}
    </div>
  );
}
