import React from 'react'
import { useScale } from '../../context/ScaleContext'
import type { EntityDisplayArea, InventoryTypeDefinition } from '../../types'
import { ENTITY_PLACEHOLDER_IMAGES } from './defaultEntityImages'

interface EntityDisplayProps {
  area: EntityDisplayArea
  placeholder: NonNullable<InventoryTypeDefinition['entityPlaceholder']>
  /** When true, draw layout debug bounds instead of the default image (ignored if renderEntity is set). */
  debug?: boolean
  renderEntity?: ((width: number, height: number) => React.ReactNode) | null
}

export function EntityDisplay({
  area,
  placeholder,
  debug = false,
  renderEntity,
}: EntityDisplayProps) {
  const { scale } = useScale()

  if (renderEntity === null) return null

  const w = area.width * scale
  const h = area.height * scale

  let content: React.ReactNode
  if (renderEntity) {
    content = renderEntity(w, h)
  } else if (debug) {
    content = (
      <div
        className="mc-inv-entity-display-placeholder"
        style={{
          width: '100%',
          height: '100%',
          background: 'rgba(255, 0, 0, 0.15)',
          border: '1px solid rgba(255, 0, 0, 0.4)',
          boxSizing: 'border-box',
        }}
      />
    )
  } else {
    const image = ENTITY_PLACEHOLDER_IMAGES[placeholder]
    if (!image) return null
    content = (
      <img
        src={ENTITY_PLACEHOLDER_IMAGES[placeholder]}
        alt=""
        draggable={false}
        className="mc-inv-entity-display-image"
        style={{
          display: 'block',
          width: '100%',
          height: '100%',
          objectFit: 'contain',
          pointerEvents: 'none',
          userSelect: 'none',
          imageRendering: 'pixelated',
        }}
      />
    )
  }

  return (
    <div
      className="mc-inv-entity-display"
      style={{
        position: 'absolute',
        left: area.x * scale,
        top: area.y * scale,
        width: w,
        height: h,
        overflow: 'hidden',
      }}
    >
      {content}
    </div>
  )
}
