import { create } from 'zustand';
import type { BasketKey } from '../fixtures/packages';

// ComparisonPage caps user-selected packages at 3 (recommended is shown as a
// separate column). Keep the basket aligned so we can't add a 4th and have it
// silently dropped at render time.
const MAX_BASKET = 3;

interface BasketState {
  packageKeys: BasketKey[];
  /** Transient feedback message — set when add() is rejected (dupe/full) */
  lastError: string | null;
  add: (key: BasketKey) => void;
  remove: (key: BasketKey) => void;
  toggle: (key: BasketKey) => void;
  clear: () => void;
  clearError: () => void;
  setAll: (keys: BasketKey[]) => void;
  has: (key: BasketKey) => boolean;
  isFull: () => boolean;
}

export const useComparisonBasket = create<BasketState>((set, get) => ({
  packageKeys: [],
  lastError: null,
  add: (key) =>
    set((state) => {
      if (state.packageKeys.includes(key)) {
        return { ...state, lastError: 'Already added' };
      }
      if (state.packageKeys.length >= MAX_BASKET) {
        return { ...state, lastError: `Maximum ${MAX_BASKET} packages` };
      }
      return { packageKeys: [...state.packageKeys, key], lastError: null };
    }),
  remove: (key) => set((state) => ({ packageKeys: state.packageKeys.filter((k) => k !== key) })),
  toggle: (key) => {
    const { has, add, remove } = get();
    if (has(key)) remove(key);
    else add(key);
  },
  clear: () => set({ packageKeys: [], lastError: null }),
  clearError: () => set({ lastError: null }),
  setAll: (keys) => set({ packageKeys: keys.slice(0, MAX_BASKET), lastError: null }),
  has: (key) => get().packageKeys.includes(key),
  isFull: () => get().packageKeys.length >= MAX_BASKET,
}));

export const BASKET_MAX = MAX_BASKET;
