import { memo } from 'react'
import type {
  ArtboardElement,
  GroupElement,
  SceneElement,
  TextElement,
} from './domino'
import { useDominoStore } from './domino-hooks'
import Placeholder from './placeholder'
import { TextRender } from './text-render'
import { ElementRenderer } from './element-renderer'

/**
 * 核心内容渲染器：只管元素长什么样
 */
function ElementContent({ element }: { element: SceneElement }) {
  const uiState = useDominoStore(state => state.elementUIStates[element.id])

  switch (element.type) {
    case 'image':
      return (
        <>
          <img
            src={element.src}
            alt={element.fileName}
            crossOrigin='anonymous'
            loading='eager'
            decoding='async'
            className='w-full h-full object-contain pointer-events-none bg-white/5'
          />
          {uiState?.status === 'pending' && (
            <Placeholder className='z-1 h-full w-full'>
              <span
                className='text-white'
                style={{ fontSize: 'calc(14px / var(--domino-scale))' }}
              >
                {uiState?.statusText}
              </span>
            </Placeholder>
          )}
        </>
      )
    case 'text': {
      return <TextRender element={element as TextElement} />
    }
    case 'group': {
      const childrenIds = (element as GroupElement).childrenIds
      return (
        <div className='relative'>
          {childrenIds.map((childId: string) => (
            <ElementRenderer key={childId} id={childId} />
          ))}
        </div>
      )
    }
    case 'artboard': {
      const childrenIds = (element as ArtboardElement).childrenIds
      return (
        <div
          className='relative w-full h-full'
          style={{
            background: element.background || '#fff',
            overflow: 'hidden',
          }}
        >
          {childrenIds.map((childId: string) => (
            <ElementRenderer key={childId} id={childId} />
          ))}
        </div>
      )
    }
    case 'placeholder':
      return (
        <Placeholder>
          <span style={{ fontSize: 'calc(16px / var(--domino-scale))' }}>
            {element.label}
          </span>
        </Placeholder>
      )
    default:
      return null
  }
}

export const MemoizedElementContent = memo(ElementContent)
