/**
 * BlockRenderer.tsx - 块渲染器组件
 * 
 * 根据block类型路由到对应的块组件
 * 
 * @module components/Editor
 */

import React from 'react';
import type { DocumentBlock } from '../../types/editor';
import { HeadingBlock } from './blocks/HeadingBlock';
import { ParagraphBlock } from './blocks/ParagraphBlock';
import { TableBlock } from './blocks/TableBlock';
import { ImageBlock } from './blocks/ImageBlock';
import { TOCBlock } from './blocks/TOCBlock';

// ══════════════════════════════════════════════════════════════════════════════
// Component Props
// ══════════════════════════════════════════════════════════════════════════════

export interface BlockRendererProps {
  /** 文档块 */
  block: DocumentBlock;
  /** 块在画布排序结果中的位置 */
  index?: number;
  /** 画布中的块总数 */
  blockCount?: number;
  /** 是否只读 */
  readOnly?: boolean;
  /** 标题是否存在可折叠内容 */
  collapsible?: boolean;
  /** 标题内容是否已折叠 */
  collapsed?: boolean;
  /** 段落列表标记 */
  listMarker?: string;
  /** 切换标题折叠状态 */
  onToggleCollapse?: () => void;
}

// ══════════════════════════════════════════════════════════════════════════════
// Component
// ══════════════════════════════════════════════════════════════════════════════

/**
 * BlockRenderer - 块渲染器
 * 
 * 根据block.type渲染对应的组件
 */
export const BlockRenderer = React.memo(function BlockRenderer({
  block,
  index,
  blockCount,
  collapsible,
  collapsed,
  listMarker,
  onToggleCollapse,
  readOnly = false,
}: BlockRendererProps) {
  switch (block.type) {
    case 'heading':
      return (
        <HeadingBlock
          block={block}
          index={index ?? 0}
          blockCount={blockCount ?? 0}
          listMarker={listMarker}
          collapsible={collapsible}
          collapsed={collapsed}
          onToggleCollapse={onToggleCollapse}
          readOnly={readOnly}
        />
      );
    
    case 'paragraph':
      return (
        <ParagraphBlock
          block={block}
          index={index ?? 0}
          blockCount={blockCount ?? 0}
          readOnly={readOnly}
          listMarker={listMarker}
        />
      );
    
    case 'table':
      return <TableBlock block={block} readOnly={readOnly} />;
    
    case 'image':
      return (
        <ImageBlock
          block={block}
          index={index ?? 0}
          blockCount={blockCount ?? 0}
          readOnly={readOnly}
        />
      );
    
    case 'toc':
      return <TOCBlock block={block} readOnly={true} />;
    
    default:
      // 未知类型,显示警告
      return (
        <div style={{ padding: '12px', backgroundColor: '#fff7e6', border: '1px solid #ffd591' }}>
          <p style={{ margin: 0, color: '#d48806' }}>
            未知的块类型: {String((block as { type?: unknown }).type)}
          </p>
        </div>
      );
  }
});

export default BlockRenderer;
