import { useContext } from "react" import { create, useStore } from "zustand" import { BookingConfirmationContext } from "@/contexts/BookingConfirmation" import type { BookingConfirmationState, InitialState, } from "@/types/stores/booking-confirmation" export function createBookingConfirmationStore(initialState: InitialState) { return create()((set) => ({ rooms: initialState.rooms, bookingCode: initialState.bookingCode, currencyCode: initialState.currencyCode, fromDate: initialState.fromDate, toDate: initialState.toDate, vat: initialState.vat, formattedTotalCost: initialState.formattedTotalCost, isVatCurrency: initialState.isVatCurrency, totalBookingPrice: initialState.totalBookingPrice, actions: { setRoom: (room, idx) => { set((state) => { const rooms = [...state.rooms] rooms[idx] = room const totalBookingPrice = rooms.reduce((acc, room) => { return acc + (room?.totalPrice ?? 0) }, 0) return { rooms, totalBookingPrice } }) }, setFormattedTotalCost: (updatedFormattedTotalCost: string) => { set((state) => { return { ...state, formattedTotalCost: updatedFormattedTotalCost } }) }, }, })) } export function useBookingConfirmationStore( selector: (store: BookingConfirmationState) => T ) { const store = useContext(BookingConfirmationContext) if (!store) { throw new Error( "useBookingConfirmationStore must be used within BookingConfirmationProvider" ) } return useStore(store, selector) }