import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { BasePlayer } from '../types';

export interface FavPlayer extends BasePlayer {
  realname?: string;
  avatar?: string;
}

interface FavPlayerStore {
  favMap: Record<string, FavPlayer>;
  fav(player: FavPlayer): void;
  unFav(uid: string): void;
  isFav(uid?: string): boolean;
}

export const useFavPlayerStore = create(persist<FavPlayerStore>((set, get) => ({
  favMap: {},
  fav: user => {
    const { favMap } = get();
    favMap[user.uid] = user;
    set({ favMap: { ...favMap } });
  },
  unFav: uid => {
    const { favMap } = get();
    delete favMap[uid];
    set({ favMap: { ...favMap } });
  },
  isFav(uid) {
    if (!uid) return false;
    return !!get().favMap[uid];
  },
}), { name: 'fav-player-store', storage: createJSONStorage(() => localStorage) }));