'use client'

import { useState } from 'react'
import type { BlockNode } from '@actuate-media/cms-core'
import { blockRenderers, FallbackPreview } from '../block-renderers/index.js'

export interface BlockRendererProps {
  node: BlockNode
  selectedNodeId: string | null
  onSelectNode: (id: string | null) => void
}

function getBlockLabel(blockType: string): string {
  return blockType.charAt(0).toUpperCase() + blockType.slice(1)
}

export function BlockRenderer({ node, selectedNodeId, onSelectNode }: BlockRendererProps) {
  const [hovered, setHovered] = useState(false)
  const isSelected = selectedNodeId === node.id
  const blockType = node.settings.blockType
  const label = getBlockLabel(blockType)
  const Preview = blockRenderers[blockType]

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    onSelectNode(node.id)
  }

  return (
    <div
      data-node-id={node.id}
      data-block-type={blockType}
      className={`relative min-h-[48px] transition-shadow ${
        isSelected ? 'ring-primary ring-2 ring-offset-2' : hovered ? 'ring-primary/50 ring-1' : ''
      }`}
      onClick={handleClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {(hovered || isSelected) && (
        <span className="bg-primary text-primary-foreground absolute -top-2 -left-1 z-10 rounded px-1.5 py-0.5 text-xs font-medium">
          {label}
        </span>
      )}

      {/* Previews are display-only on the canvas; the wrapper owns selection. */}
      <div className="pointer-events-none">
        {Preview ? (
          <Preview data={node.data} variant={node.settings.variant} />
        ) : (
          <FallbackPreview blockType={blockType} data={node.data} />
        )}
      </div>
    </div>
  )
}
