import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import type { GameState, Card, Player } from '@/types'

export const useGameStore = defineStore('game', () => {
  const gameState = ref<GameState | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Computed properties for current player's view
  const myPlayer = computed<Player | null>(() => {
    if (!gameState.value) return null
    return gameState.value.players.find(p => p.isMe) ?? null
  })

  const opponent = computed<Player | null>(() => {
    if (!gameState.value) return null
    return gameState.value.players.find(p => !p.isMe) ?? null
  })

  const myHand = computed<Card[]>(() => myPlayer.value?.hand ?? [])

  const myActive = computed<Card | null>(() => myPlayer.value?.active ?? null)

  const myBench = computed<Card[]>(() => myPlayer.value?.bench ?? [])

  const isMyTurn = computed(() => {
    if (!gameState.value || !myPlayer.value) return false
    return gameState.value.currentPlayerId === myPlayer.value.id
  })

  const currentPhase = computed(() => gameState.value?.phase ?? null)

  // Actions
  function updateGameState(state: GameState) {
    gameState.value = state
  }

  function clearGame() {
    gameState.value = null
    error.value = null
  }

  function setError(message: string) {
    error.value = message
  }

  function clearError() {
    error.value = null
  }

  return {
    // State
    gameState,
    isLoading,
    error,

    // Computed
    myPlayer,
    opponent,
    myHand,
    myActive,
    myBench,
    isMyTurn,
    currentPhase,

    // Actions
    updateGameState,
    clearGame,
    setError,
    clearError,
  }
})
