import AsyncStorage from "@react-native-async-storage/async-storage"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; export type Fulfillment = "delivery" | "pickup"; export type PaymentMethod = | "chapa" | "arifpay" | "telebirr" | "mpesa" | "bank" | "cod" | "pay_at_branch"; type LocationState = { fulfillment: Fulfillment; areaLabel: string; branchId: string | null; lat: number | null; lng: number | null; paymentPreference: PaymentMethod; setFulfillment: (f: Fulfillment) => void; setAreaLabel: (label: string) => void; setBranchId: (id: string | null) => void; setCoords: (lat: number | null, lng: number | null) => void; setPaymentPreference: (m: PaymentMethod) => void; allowedPayments: () => PaymentMethod[]; }; export const useLocationStore = create()( persist( (set, get) => ({ fulfillment: "delivery", areaLabel: "Addis Ababa", branchId: null, lat: null, lng: null, paymentPreference: "chapa", setFulfillment: (fulfillment) => { const next: Partial = { fulfillment }; if ( fulfillment === "delivery" && (get().paymentPreference === "pay_at_branch" || get().paymentPreference === "cod") ) { // COD stays valid for delivery; only strip pay_at_branch if (get().paymentPreference === "pay_at_branch") { next.paymentPreference = "chapa"; } } if (fulfillment === "pickup" && get().paymentPreference === "cod") { next.paymentPreference = "pay_at_branch"; } set(next); }, setAreaLabel: (areaLabel) => set({ areaLabel }), setBranchId: (branchId) => set({ branchId }), setCoords: (lat, lng) => set({ lat, lng }), setPaymentPreference: (paymentPreference) => set({ paymentPreference }), allowedPayments: () => { const online: PaymentMethod[] = [ "chapa", "arifpay", "telebirr", "mpesa", "bank", ]; return get().fulfillment === "pickup" ? [...online, "pay_at_branch"] : [...online, "cod"]; }, }), { name: "gishen-location", storage: createJSONStorage(() => AsyncStorage), version: 2, } ) );