import { useGame } from '../../contexts/game-context'
import Entity from '../entity/entity'
import type { GameEntity } from '../../types'

export default function Space ({ space }: { space: GameEntity }) {
  const { clickTarget, allClickable, currentMoveTargets } = useGame()
  const { entities, entityId } = space.attributes

  const entityList = entities ?? []
  const clickable = allClickable.has(space)
  const targeted = currentMoveTargets
    .map((e) => (e as GameEntity).entityId ?? (e as GameEntity).attributes?.entityId)
    .includes(entityId)

  return (
    <a
      className={[
        'space',
        clickable && 'space--clickable',
        targeted && 'space--targeted',
      ].filter(Boolean).join(' ')}
      onClick={() => clickTarget(space)}
      style={{
        display: 'inline-block',
        flex: '1',
      }}
    >
      <div
        className="space__entity-grid"
        style={{
          display: 'flex',
          height: '100%',
          width: '100%',
          flexWrap: 'wrap',
        }}
      >
        {Array.from({ length: entityList.length }, (_, i) => (
          <div
            className="space__entity-grid__cell"
            style={{
              display: 'inline-block',
            }}
            key={i}
          >
            <Entity entity={entityList[i]} />
          </div>
        ))}
        {!entityList.length && String(space.attributes.name ?? '')}
      </div>
    </a>
  )
}
