import { defineStore } from 'pinia'
import type { Track } from '~/../types/types'

export const FAVORITES_BOX_ID = 'FAV'
const STORAGE_KEY = 'evilspins:favorites:v1'

export const useFavoritesStore = defineStore('favorites', {
  state: () => ({
    trackIds: [] as number[]
  }),
  actions: {
    load() {
      if (!process.client) return
      try {
        const raw = localStorage.getItem(STORAGE_KEY)
        if (raw) {
          const arr = JSON.parse(raw)
          if (Array.isArray(arr)) this.trackIds = arr.filter((x) => typeof x === 'number')
        }
      } catch {}
    },
    save() {
      if (!process.client) return
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(this.trackIds))
      } catch {}
    },
    toggle(track: Track) {
      const id = track.id
      const idx = this.trackIds.indexOf(id)
      if (idx >= 0) this.trackIds.splice(idx, 1)
      else this.trackIds.unshift(id)
      this.save()
    },
    add(track: Track) {
      if (!this.trackIds.includes(track.id)) {
        this.trackIds.unshift(track.id)
        this.save()
      }
    },
    remove(trackId: number) {
      const idx = this.trackIds.indexOf(trackId)
      if (idx >= 0) {
        this.trackIds.splice(idx, 1)
        this.save()
      }
    },
    isFavorite(trackId: number) {
      return this.trackIds.includes(trackId)
    }
  }
})
