import { create } from 'zustand';

export interface DealSelection {
  listingId: string;
  title: string;
  category: string;
  value: number;
  sellerId: string;
  sellerName: string;
}

interface DealState {
  selections: DealSelection[];
  isOpen: boolean;

  addSelection: (item: DealSelection) => void;
  removeSelection: (listingId: string) => void;
  clearSelections: () => void;
  isSelected: (listingId: string) => boolean;
  togglePanel: () => void;
  openPanel: () => void;
  closePanel: () => void;

  getSelectionCount: () => number;
  /** Group selections by seller for multi-seller deals */
  getGroupedBySeller: () => Record<string, DealSelection[]>;
}

export const useDealStore = create<DealState>()((set, get) => ({
  selections: [],
  isOpen: false,

  addSelection: (item) => {
    set((state) => {
      if (state.selections.find(s => s.listingId === item.listingId)) return state;
      return { selections: [...state.selections, item], isOpen: true };
    });
  },

  removeSelection: (listingId) => {
    set((state) => ({
      selections: state.selections.filter(s => s.listingId !== listingId),
    }));
  },

  clearSelections: () => set({ selections: [] }),

  isSelected: (listingId) => {
    return get().selections.some(s => s.listingId === listingId);
  },

  togglePanel: () => set((s) => ({ isOpen: !s.isOpen })),
  openPanel: () => set({ isOpen: true }),
  closePanel: () => set({ isOpen: false }),

  getSelectionCount: () => get().selections.length,

  getGroupedBySeller: () => {
    const groups: Record<string, DealSelection[]> = {};
    for (const s of get().selections) {
      if (!groups[s.sellerName]) groups[s.sellerName] = [];
      groups[s.sellerName].push(s);
    }
    return groups;
  },
}));
