// Bookmark Store

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface BookmarkState {
  bookmarkedIds: Set<string>;
  
  // Actions
  addBookmark: (articleId: string) => void;
  removeBookmark: (articleId: string) => void;
  toggleBookmark: (articleId: string) => void;
  isBookmarked: (articleId: string) => boolean;
  getBookmarks: () => string[];
}

export const useBookmarkStore = create<BookmarkState>()(
  persist(
    (set, get) => ({
      bookmarkedIds: new Set<string>(),
      
      addBookmark: (articleId: string) =>
        set((state) => ({
          bookmarkedIds: new Set([...state.bookmarkedIds, articleId]),
        })),
        
      removeBookmark: (articleId: string) =>
        set((state) => {
          const newSet = new Set(state.bookmarkedIds);
          newSet.delete(articleId);
          return { bookmarkedIds: newSet };
        }),
        
      toggleBookmark: (articleId: string) =>
        set((state) => {
          const newSet = new Set(state.bookmarkedIds);
          if (newSet.has(articleId)) {
            newSet.delete(articleId);
          } else {
            newSet.add(articleId);
          }
          return { bookmarkedIds: newSet };
        }),
        
      isBookmarked: (articleId: string) =>
        get().bookmarkedIds.has(articleId),
        
      getBookmarks: () =>
        Array.from(get().bookmarkedIds),
    }),
    {
      name: 'rssuper-bookmarks',
      storage: createJSONStorage(() => AsyncStorage),
      partialize: (state) => ({
        bookmarkedIds: Array.from(state.bookmarkedIds),
      }),
      merge: (persisted: any, current) => ({
        ...current,
        bookmarkedIds: new Set(persisted?.bookmarkedIds || []),
      }),
    }
  )
);