import { create } from 'zustand'
import type { UnifiedMatchResult } from '../domain/unifiedResult'

const MAX_COMPARE_ITEMS = 4

interface CompareState {
  compareItems: UnifiedMatchResult[]
  addToCompare: (result: UnifiedMatchResult) => void
  removeFromCompare: (matchId: string) => void
  clearCompare: () => void
  isInCompare: (matchId: string) => boolean
  isFull: () => boolean
}

export const useCompareStore = create<CompareState>((set, get) => ({
  compareItems: [],
  addToCompare: (result) =>
    set((state) => {
      if (state.compareItems.length >= MAX_COMPARE_ITEMS) return state
      if (state.compareItems.some(i => i.matchId === result.matchId)) return state
      return { compareItems: [...state.compareItems, result] }
    }),
  removeFromCompare: (matchId) =>
    set((state) => ({ compareItems: state.compareItems.filter(i => i.matchId !== matchId) })),
  clearCompare: () => set({ compareItems: [] }),
  isInCompare: (matchId) => get().compareItems.some(i => i.matchId === matchId),
  isFull: () => get().compareItems.length >= MAX_COMPARE_ITEMS,
}))
