import type { ReactNode } from 'react'
import Entity from '../entity/entity'
import AbstractChoices from '../abstract-choices/abstract-choices'
import GameStatus from '../game-status/game-status'
import { GameProvider } from '../../contexts/game-context'
import type { GameEntity, GameserverConnection } from '../../types'

export default function Game ({
  gameConnection,
  loading,
  isSpectator,
}: {
  gameConnection?: GameserverConnection | Record<string, never> | null
  loading?: ReactNode
  isSpectator?: boolean
}) {
  const G = gameConnection && 'state' in gameConnection
    ? (gameConnection as unknown as GameserverConnection).state?.G as
        | { sharedBoard: { entities: GameEntity[] }; personalBoards?: { entities: GameEntity[] }[] }
        | undefined
    : undefined

  return G
    ? (
      <GameProvider
        gameConnection={gameConnection as GameserverConnection}
        isSpectator={isSpectator}
      >
        <div className="game">
          <AbstractChoices />
          <div
            className="shared-board"
            style={{
              width: '100%',
              display: 'flex',
              flexWrap: 'wrap',
              justifyContent: 'center',
              alignItems: 'center',
              gap: '1em',
            }}
          >
            {G.sharedBoard.entities.map((entity, i) => <Entity key={i} entity={entity} />)}
          </div>
          {G.personalBoards && (
            <div className="personal-boards">
              {G.personalBoards.map((board, i) => (
                <div
                  key={i}
                  className="personal-board"
                  style={{
                    width: '100%',
                    display: 'grid',
                    gridAutoFlow: 'column',
                    gridAutoRows: '1fr',
                    gap: '1em',
                  }}
                >
                  {board.entities.map((entity, j) => (
                    <Entity key={j} entity={entity} />
                  ))}
                </div>
              ))}
            </div>
          )}
          <GameStatus gameConnection={gameConnection as GameserverConnection} />
        </div>
      </GameProvider>
    )
    : loading
}
