import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface FavoritesState {
  favorites: string[];
}

interface FavoritesActions {
  addFavorite: (key: string) => void;
  removeFavorite: (key: string) => void;
  toggleFavorite: (key: string) => void;
  isFavorite: (key: string) => boolean;
}

export const useFavoritesStore = create<FavoritesState & FavoritesActions>()(
  persist(
    (set, get) => ({
      favorites: [],

      addFavorite: (key: string) => {
        const { favorites } = get();
        if (!favorites.includes(key)) {
          set({ favorites: [...favorites, key] });
        }
      },

      removeFavorite: (key: string) => {
        set({ favorites: get().favorites.filter(k => k !== key) });
      },

      toggleFavorite: (key: string) => {
        const { favorites } = get();
        if (favorites.includes(key)) {
          set({ favorites: favorites.filter(k => k !== key) });
        } else {
          set({ favorites: [...favorites, key] });
        }
      },

      isFavorite: (key: string) => get().favorites.includes(key),
    }),
    {
      name: 'cml-favorites',
      partialize: (state) => ({ favorites: state.favorites }),
    }
  )
);
