import type { GameserverConnection } from '../../types'

export default function GameStatus ({
  gameConnection,
}: {
  gameConnection: GameserverConnection
}) {
  const state = gameConnection.state
  if (!state) return null

  const players = gameConnection.client?.matchData as
    | Record<string, { name?: string }>
    | undefined
  const winner = state.ctx.gameover?.winner as string | number | undefined
  const draw = state.ctx.gameover?.draw
  let winnerString = ''
  if (draw) {
    winnerString = 'Draw!'
  } else if (players != null && winner != null && winner !== '') {
    const key = String(winner)
    winnerString = `${players[key]?.name ?? ''} Wins!`
  } else if (winner != null && winner !== '') {
    winnerString = `Player ${String(winner)} Wins!`
  }
  return state.ctx.gameover && (
    <div className="game-status">
      {winnerString}
    </div>
  )
}
