import { ICraftableItem } from '@rpg-engine/shared';
import { useMemo } from 'react';

interface UseCraftBookFiltersProps {
  items: ICraftableItem[];
  searchTerm: string;
  selectedType: string;
  pinnedItems: string[];
}

export const useCraftBookFilters = ({
  items,
  searchTerm,
  selectedType,
  pinnedItems,
}: UseCraftBookFiltersProps): ICraftableItem[] => {
  return useMemo(() => {
    // First filter items
    const filteredItems = items?.filter(item => {
      const matchesSearch = item.name
        .toLowerCase()
        .includes(searchTerm.toLowerCase());
      const matchesCategory =
        selectedType === 'Suggested' ||
        (selectedType === 'Pinned' && pinnedItems.includes(item.key)) ||
        item.type === selectedType;
      return matchesSearch && matchesCategory;
    });

    // Then sort them (pinned items first)
    return [...(filteredItems || [])].sort((a, b) => {
      const aIsPinned = pinnedItems.includes(a.key);
      const bIsPinned = pinnedItems.includes(b.key);
      if (aIsPinned && !bIsPinned) return -1;
      if (!aIsPinned && bIsPinned) return 1;
      return 0;
    });
  }, [items, searchTerm, selectedType, pinnedItems]);
};
