import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { createUserStorage } from './utils/userStorage';

export interface FavoriteItem {
  id: string;
  label: string;
  iconName: string;
  path: string;
  addedAt: number;
}

export const MAX_FAVORITES = 10;

interface FavoritesState {
  favorites: FavoriteItem[];
  toggleFavorite: (item: FavoriteItem) => 'added' | 'removed' | 'max_reached';
  isFavorite: (id: string) => boolean;
  setFavorites: (items: FavoriteItem[]) => void;
  initializeIfEmpty: (defaults: FavoriteItem[]) => void;
}

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

      toggleFavorite: (item: FavoriteItem) => {
        const { favorites } = get();
        const exists = favorites.some((f) => f.id === item.id);

        if (exists) {
          set({ favorites: favorites.filter((f) => f.id !== item.id) });
          return 'removed';
        } else {
          if (favorites.length >= MAX_FAVORITES) return 'max_reached';
          set({ favorites: [...favorites, { ...item, addedAt: Date.now() }] });
          return 'added';
        }
      },

      isFavorite: (id: string) => {
        return get().favorites.some((f) => f.id === id);
      },

      setFavorites: (items: FavoriteItem[]) => {
        set({ favorites: items.slice(0, MAX_FAVORITES) });
      },

      initializeIfEmpty: (defaults: FavoriteItem[]) => {
        const { favorites } = get();
        if (favorites.length === 0) {
          set({ favorites: defaults.slice(0, MAX_FAVORITES) });
        }
      },
    }),
    {
      name: 'sam-favorites',
      storage: createUserStorage('sam-favorites'),
    }
  )
);
