import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { submissionsApiListPuzzles } from '@/api'
import type { SteamCollectionItem } from '@/types'

export const usePuzzlesStore = defineStore('puzzles', () => {
  // State
  const puzzles = ref<SteamCollectionItem[]>([])
  const isLoading = ref(false)
  const error = ref<string>('')

  // Getters
  const puzzleNames = computed(() => puzzles.value.map(puzzle => puzzle.title))
  
  const findPuzzleByName = computed(() => (name: string): SteamCollectionItem | null => {
    if (!name) return null

    // First try exact match (case insensitive)
    const exactMatch = puzzles.value.find(
      puzzle => puzzle.title.toLowerCase() === name.toLowerCase()
    )
    if (exactMatch) return exactMatch

    // Then try partial match
    const partialMatch = puzzles.value.find(
      puzzle => puzzle.title.toLowerCase().includes(name.toLowerCase()) ||
                name.toLowerCase().includes(puzzle.title.toLowerCase())
    )

    return partialMatch || null
  })

  // Actions
  const loadPuzzles = async () => {
    if (puzzles.value.length > 0) return // Already loaded

    try {
      isLoading.value = true
      error.value = ''

      const response = await submissionsApiListPuzzles()
      if (response.error) {
        error.value = String(response.error)
        console.error('Failed to load puzzles:', response.error)
        return
      }

      if (response.data) {
        puzzles.value = response.data as unknown as SteamCollectionItem[]
      }
    } catch (err) {
      error.value = 'Failed to load puzzles'
      console.error('Error loading puzzles:', err)
    } finally {
      isLoading.value = false
    }
  }

  const refreshPuzzles = async () => {
    puzzles.value = []
    await loadPuzzles()
  }

  return {
    // State
    puzzles,
    isLoading,
    error,
    
    // Getters
    puzzleNames,
    findPuzzleByName,
    
    // Actions
    loadPuzzles,
    refreshPuzzles
  }
})
