'use client'

import * as React from 'react'
import { Block, MergeFieldDefinition } from './types'
import {
  TextBlockEditor,
  MetricsBlockEditor,
  DividerBlockEditor,
  ButtonBlockEditor,
  ImageBlockEditor,
  SpacerBlockEditor,
  SocialBlockEditor,
  HeaderBlockEditor,
  FooterBlockEditor,
} from './blocks'

interface BlockRendererProps {
  block: Block
  editing: boolean
  onChange: (updates: Partial<Block>) => void
  mergeFields: MergeFieldDefinition[]
  /** Optional custom rich text editor for the text block. */
  renderTextEditor?: (props: {
    content: string
    onChange: (html: string) => void
    placeholder?: string
    className?: string
  }) => React.ReactNode
}

export function BlockRenderer({
  block,
  editing,
  onChange,
  mergeFields: _mergeFields,
  renderTextEditor,
}: BlockRendererProps) {
  const commonProps = {
    isEditing: editing,
    onChange: onChange as (block: Block) => void,
  }

  switch (block.type) {
    case 'text':
      return (
        <TextBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
          renderEditor={renderTextEditor}
        />
      )
    case 'metrics':
      return (
        <MetricsBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'divider':
      return (
        <DividerBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'cta':
      return (
        <ButtonBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'image':
      return (
        <ImageBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'spacer':
      return (
        <SpacerBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'social':
      return (
        <SocialBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'header':
      return (
        <HeaderBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    case 'footer':
      return (
        <FooterBlockEditor
          block={block}
          {...commonProps}
          onChange={(b) => onChange(b)}
        />
      )
    default:
      return null
  }
}
