import { create } from "zustand";

interface TicketStore {
  amenities: number[];
  id: number | null;
  setId: (id: number) => void;
  setAmenities: (amenities: number[]) => void;
  addAmenity: (amenity: number) => void;
  removeAmenity: (id: number) => void;
  updateAmenity: (index: number, updated: number) => void;
}

export const useTicketStore = create<TicketStore>((set) => ({
  amenities: [],
  id: null,

  setId: (id) => set({ id }),

  setAmenities: (amenities) => set({ amenities }),

  addAmenity: (amenity) =>
    set((state) => {
      // agar qulaylik allaqachon mavjud bo‘lsa, qo‘shmaydi
      if (state.amenities.includes(amenity)) return state;
      return { amenities: [...state.amenities, amenity] };
    }),

  removeAmenity: (id) =>
    set((state) => ({
      amenities: state.amenities.filter((a) => a !== id),
    })),

  updateAmenity: (index, updated) =>
    set((state) => {
      const newAmenities = [...state.amenities];
      if (index >= 0 && index < newAmenities.length) {
        newAmenities[index] = updated;
      }
      return { amenities: newAmenities };
    }),
}));
