import {
  createContext,
  useContext,
  useEffect,
  type ReactNode,
} from 'react'
import type { GameserverConnection } from '../types'

export interface GameContextValue {
  clickTarget: (target: unknown) => void
  undoStep: () => void
  allClickable: Set<unknown>
  currentMoveTargets: unknown[]
}

const GameContext = createContext<GameContextValue>({
  clickTarget: () => {},
  undoStep: () => {},
  allClickable: new Set(),
  currentMoveTargets: [],
})

export function GameProvider ({
  gameConnection,
  children,
  isSpectator,
}: {
  gameConnection: GameserverConnection
  children: ReactNode
  isSpectator?: boolean
}) {
  useEffect(() => {
    if (gameConnection.state?._stateID === 0) {
      gameConnection.reset()
    }
  }, [gameConnection.state?._stateID])

  return (
    <GameContext.Provider
      value={{
        clickTarget: (target: unknown) => {
          if (!isSpectator) {
            gameConnection.doStep(target)
          }
        },
        undoStep: () => { gameConnection.undoStep() },
        allClickable: (gameConnection.optimisticWinner || isSpectator)
          ? new Set()
          : (gameConnection.allClickable ?? new Set()),
        currentMoveTargets: (gameConnection.optimisticWinner || isSpectator)
          ? []
          : (gameConnection.moveBuilder?.targets ?? []),
      }}
    >
      {children}
    </GameContext.Provider>
  )
}

export const useGame = () => useContext(GameContext)
