import { useEffect, useRef, type MutableRefObject } from 'react'
import Phaser from 'phaser'
import type { MovementVector } from '../../../input'
import { BulldromeArenaScene } from './scenes/BulldromeArenaScene'
import type { Iwt2ArenaState } from '../sim/arenaState'

type PhaserArenaProps = {
  movementRef: MutableRefObject<MovementVector>
  selectedPartyIdRef: MutableRefObject<string>
  stateRef: MutableRefObject<Iwt2ArenaState>
  onStep: (movement: MovementVector, dtSeconds: number) => Iwt2ArenaState
}

export function PhaserArena({ movementRef, onStep, selectedPartyIdRef, stateRef }: PhaserArenaProps) {
  const hostRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (!hostRef.current) return undefined
    const initialState = stateRef.current
    const scene = new BulldromeArenaScene({
      getMovement: () => movementRef.current,
      getSelectedPartyId: () => selectedPartyIdRef.current,
      getState: () => stateRef.current,
      step: onStep,
    })
    const game = new Phaser.Game({
      type: Phaser.AUTO,
      parent: hostRef.current,
      width: initialState.bounds.width,
      height: initialState.bounds.height,
      backgroundColor: '#10141b',
      pixelArt: false,
      scale: {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
      },
      scene,
    })

    return () => {
      game.destroy(true)
    }
  }, [movementRef, onStep, selectedPartyIdRef, stateRef])

  return <div className="iwt2-phaser-host" ref={hostRef} />
}
