import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { Article } from '../types';

interface BookmarkState {
  bookmarks: Article[];
  addBookmark: (article: Article) => void;
  removeBookmark: (articleId: string) => void;
  isBookmarked: (articleId: string) => boolean;
}

export const useBookmarkStore = create<BookmarkState>()(
  persist(
    (set, get) => ({
      bookmarks: [],
      addBookmark: (article) => {
        if (!get().isBookmarked(article.id)) {
          set((state) => ({
            bookmarks: [...state.bookmarks, article],
          }));
        }
      },
      removeBookmark: (articleId) => {
        set((state) => ({
          bookmarks: state.bookmarks.filter((article) => article.id !== articleId),
        }));
      },
      isBookmarked: (articleId) => {
        return get().bookmarks.some((article) => article.id === articleId);
      },
    }),
    {
      name: 'bookmarks-storage',
    }
  )
);