import { useEffect, useMemo, useRef, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import type { RegionSummary, RegionBoundSummary } from '@packages/shared' import { useRegionStore } from '@/src/store/regionStore' import { useAddressStore } from '@/src/store/addressStore' import { useLocationStore } from '@/src/store/locationStore' import { trpc } from '@/src/trpc-client' import { confirmRegionSwitch } from '@/src/lib/region-switch' import { readCachedRegions, readCachedUserAddresses, writeCachedRegions, writeCachedUserAddresses, type CachedUserAddressesResponse, } from '@/src/lib/region-cache' import { useAuthOptional } from '@/src/contexts/AuthContext' // Give up on the backend resolve and fall back to the saved region / chooser. const RESOLVE_TIMEOUT_MS = 8000 // The startup location check runs ONCE per app launch, no matter how many // components consume `useRegion`. `startupCheckDone` is the single-flight guard // for the switch itself; `startupLaunchRegionId` records the region at launch so // a manual pick made before the fix lands is respected. let startupCheckDone = false let startupLaunchRegionId: number | null | undefined /** * The single source of truth for the browsing region ("location"). * * EVERY component/hook that needs to read or change the current region must go * through this hook instead of touching `useRegionStore` / `useLocationStore` * directly, so the location bar, the region gate, checkout and the regional API * hooks can never drift out of sync. * * On every launch the hook takes ONE device fix (no movement tracking) and * resolves it to a region. The active bound is NOT taken from the location; it is * the least-priority bound among the user's addresses in that region (else the * region's effective bound). If the resolved region differs from the saved one * the region is switched (clears carts, refreshes region-scoped data). When the * location is unusable the saved region is kept, or the chooser is shown. * * A sole saved address (even when it is not flagged as default) is treated as * the delivery anchor: there is only one place the user can receive an order, so * it opens directly instead of asking them to pick it from a one-item list. */ export interface UseRegionResult { /** The region the user is currently browsing. `null` until one is chosen. */ region: RegionSummary | null /** Convenience alias for `region?.id`. `null` until a region is chosen. */ regionId: number | null /** The bound whose consts the client reads for this region. `null` until known. */ boundId: number | null /** The bound the launch location fell inside, when it resolved the region. */ bound: RegionBoundSummary | null /** Monotonic marker bumped on every region change; use it to ignore stale responses. */ regionGeneration: number /** Always true: the region store is in-memory (not persisted). */ hydrated: boolean /** Latest device coordinates, if the launch fix succeeded. */ coords: { latitude: number; longitude: number } | null /** Current state of the launch location read. */ locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'services-off' | 'unavailable' | 'error' /** * True while the launch location check is still determining a region AND no * region is known yet. The UI should show a spinner rather than the chooser * while this is true. It never becomes true again after the check settles. */ isResolvingRegion: boolean /** Persist a new browsing region. For user-facing switches prefer `confirmRegionSwitch`. */ setRegion: (region: RegionSummary, boundId?: number | null) => void /** Forget the browsing region (forces the region gate to prompt again). */ clearRegion: () => void /** Re-check permission and take a fresh fix (e.g. a "use my location" button). */ refreshLocation: () => void } export function useRegion(): UseRegionResult { const queryClient = useQueryClient() const utils = trpc.useUtils() const auth = useAuthOptional() // Components above AuthProvider (UpdateChecker / HealthTestWrapper / // WebViewWrapper, through useGetEssentialConsts) also consume this hook. // They have no auth context and must not settle the launch decision: without // auth they cannot see the default/sole address, and would force the address // chooser even when the user has a default address. const hasAuthContext = auth != null const isAuthenticated = auth?.isAuthenticated ?? false const isAuthLoading = auth?.isLoading ?? false const userId = auth?.user?.id ?? null const region = useRegionStore((state) => state.selectedRegion) const regionId = useRegionStore((state) => state.selectedRegionId) const storedBoundId = useRegionStore((state) => state.selectedBoundId) const regionGeneration = useRegionStore((state) => state.regionGeneration) const setRegion = useRegionStore((state) => state.setRegion) const clearRegion = useRegionStore((state) => state.clearRegion) const coords = useLocationStore((state) => state.coords) const locationStatus = useLocationStore((state) => state.status) const startTracking = useLocationStore((state) => state.start) const refreshTracking = useLocationStore((state) => state.refresh) // The region store is in-memory (not persisted), so there is nothing to // hydrate before we can decide. const hydrated = true // True once the launch location check has a definitive outcome. const [startupResolved, setStartupResolved] = useState(false) // Last persisted startup responses. These are only the seed: the live tRPC // queries below always run and replace them (and the storage snapshot). const [cacheSnapshot, setCacheSnapshot] = useState<{ ready: boolean regions: RegionSummary[] | null addresses: CachedUserAddressesResponse | null }>({ ready: false, regions: null, addresses: null }) const cacheBaselineRef = useRef<{ regions: RegionSummary[] | null addresses: CachedUserAddressesResponse | null } | null>(null) const decisionSignatureRef = useRef(null) // The user's default address — the anchor for the startup region decision. const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, { enabled: hydrated && isAuthenticated, staleTime: 60000, }) // A sole address is a valid anchor even when it is not flagged as default. // Query the list only for signed-in users; the result is shared with the // location bar / checkout through the same React Query cache entry. const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { enabled: hydrated && isAuthenticated, staleTime: 60000, }) // Load the last snapshots before the launch decision runs. Seeding React // Query makes the cached values available to every consumer of the same // query; updatedAt: 0 keeps the entry stale so the live request still fires. useEffect(() => { let cancelled = false setCacheSnapshot({ ready: false, regions: null, addresses: null }) void (async () => { const cachedRegions = await readCachedRegions() const cachedAddresses = isAuthenticated && userId != null ? await readCachedUserAddresses(userId) : null if (cancelled) return cacheBaselineRef.current = { regions: cachedRegions, addresses: cachedAddresses } setCacheSnapshot({ ready: true, regions: cachedRegions, addresses: cachedAddresses }) if (cachedRegions && utils.common.listRegions.getData(undefined) === undefined) { utils.common.listRegions.setData(undefined, cachedRegions, { updatedAt: 0 }) } if ( cachedAddresses && userId != null && utils.user.address.getUserAddresses.getData(undefined) === undefined ) { utils.user.address.getUserAddresses.setData(undefined, cachedAddresses as any, { updatedAt: 0, }) } })() return () => { cancelled = true } }, [isAuthenticated, userId, utils]) const addresses = addressesQuery.data?.data ?? cacheSnapshot.addresses?.data ?? null const cachedDefaultAddress = cacheSnapshot.addresses?.data.find((address) => address.isDefault) ?? null const defaultAddress = defaultAddressQuery.data !== undefined ? defaultAddressQuery.data.data ?? null : cachedDefaultAddress const soleAddress = !defaultAddress && addresses?.length === 1 ? addresses[0] : null // Region summaries (needed to build the RegionSummary when adopting a region // from the default address). const regionsQuery = trpc.common.listRegions.useQuery(undefined, { enabled: hydrated, staleTime: 60000, }) const regions = regionsQuery.data ?? cacheSnapshot.regions ?? null // Signature of the data the launch decision is based on. Used to notice when // the background response differs from the cached snapshot and re-reconcile. const regionDataSignature = useMemo( () => JSON.stringify({ regions: (regions ?? []).map((region) => [ region.id, region.name, region.description, region.effectiveBoundId, ]), addresses: (addresses ?? []).map((address) => [ address.id, address.regionId, address.boundId, address.isDefault, ]), }), [regions, addresses] ) // Persist live responses. The cache writer de-duplicates identical payloads, // so the many useRegion observers do not rewrite the same snapshot. useEffect(() => { if (!regionsQuery.data) return void writeCachedRegions(regionsQuery.data) }, [regionsQuery.data]) useEffect(() => { if (userId == null || !addressesQuery.data) return void writeCachedUserAddresses(userId, addressesQuery.data) }, [userId, addressesQuery.data]) // Active bound = the least-priority bound among the user's addresses in the // region, else the region's effective bound. Derived server-side (the client // does not know bound priorities). const activeBoundQuery = trpc.common.activeBound.useQuery( { regionId: regionId ?? 0 }, { enabled: hydrated && regionId != null, staleTime: 60000 } ) const activeBoundId = activeBoundQuery.data?.boundId ?? region?.effectiveBoundId ?? null // Keep the stored bound in sync with the derived active bound (region-level). useEffect(() => { if (regionId == null || !region) return // Only fill in a MISSING bound. Never overwrite a bound already resolved // from the device location or a chosen address: those win at startup. if (storedBoundId == null && activeBoundId != null) { setRegion(region, activeBoundId) } }, [regionId, region, activeBoundId, storedBoundId, setRegion]) const boundId = storedBoundId ?? activeBoundId // Take the single launch fix — even when a region is already saved, so a // device that has moved to another region is detected on startup. useEffect(() => { if (!hydrated) return if (startupLaunchRegionId === undefined) startupLaunchRegionId = regionId startTracking() }, [hydrated, regionId, startTracking]) // Stable, rounded input so GPS jitter doesn't churn the query key. const lat = coords ? Math.round(coords.latitude * 1e5) / 1e5 : 0 const lng = coords ? Math.round(coords.longitude * 1e5) / 1e5 : 0 const queryInput = useMemo(() => ({ lat, lng }), [lat, lng]) const shouldResolve = hydrated && coords != null && !startupResolved const resolution = trpc.common.resolveRegionByLocation.useQuery(queryInput, { enabled: shouldResolve, staleTime: Infinity, retry: false, refetchOnWindowFocus: false, }) // Apply the launch outcome once. The default address anchors the decision: // - location resolves to the default's region, or to no serviceable region // (location off / out of area) -> use the default address; // - location resolves to a DIFFERENT serviceable region -> let the user pick. // A sole saved address is the exception: there is only one delivery option, so // it always wins and is opened directly (even if it is not marked default). // Without any anchor we keep the previous behaviour (use the resolved region, // else let the user pick). useEffect(() => { if (!hydrated || startupResolved) return // Only the instance below AuthProvider owns the one-shot launch decision. // An instance above it sees no user, so settling there would skip the // default-address anchor and show the chooser on every location-off launch. if (!hasAuthContext) return const resolved = resolution.data const locationSettled = resolved != null || resolution.isFetched || resolution.isError || locationStatus === 'denied' || locationStatus === 'services-off' || locationStatus === 'unavailable' || locationStatus === 'error' if (!locationSettled) return // Wait for auth to settle so signed-in users can anchor on the default // address (otherwise we'd settle with isAuthenticated=false and never // reconsider). if (isAuthLoading) return // Wait for the persisted snapshots to be read before deciding. if (!cacheSnapshot.ready) return // Signed-in users: wait for the default address and the address list (+ // regions) so a sole address can anchor the decision before we settle. // `isFetched` matters here: a query that just flipped from disabled (auth // was still loading) can report `isLoading: false` for one render before its // first request starts, which would make us settle with no addresses. // A cached snapshot is already usable while the live request is in flight. if (isAuthenticated) { const cachedAddressesAvailable = cacheSnapshot.addresses != null if ( !defaultAddressQuery.isFetched && !defaultAddressQuery.isError && !cachedAddressesAvailable ) { return } if ( !addressesQuery.isFetched && !addressesQuery.isError && !cachedAddressesAvailable ) { return } if ((defaultAddress?.regionId ?? soleAddress?.regionId) != null && !regions) return } decisionSignatureRef.current = regionDataSignature setStartupResolved(true) // Only one consumer performs the switch; the rest just settle their spinner. if (startupCheckDone) return startupCheckDone = true // Respect a manual pick made before the fix resolved. const userChangedRegion = startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId if (userChangedRegion) return const anchorAddress = defaultAddress ?? soleAddress const anchorRegionId = isAuthenticated ? anchorAddress?.regionId ?? null : null // A sole address is the only place we can deliver, so it wins even when the // launch location resolves to a different serviceable region. const soleAddressWins = isAuthenticated && soleAddress?.regionId != null if (anchorRegionId != null) { const inAnchorRegion = resolved?.region?.id === anchorRegionId // No serviceable region found -> treat like a disabled location. const noServiceableRegion = resolved == null if (soleAddressWins || inAnchorRegion || noServiceableRegion) { const region = regions?.find((candidate) => candidate.id === anchorRegionId) ?? null if (region) { // Picking the sole address also makes it the active delivery address, // so the bar / checkout don't fall back to "no address". const selectSoleAddress = () => { if (soleAddress != null) { useAddressStore.getState().setSelectedAddressId(soleAddress.id) } } if (regionId == null) { // First region of this launch — adopt it without clearing the cart. setRegion(region, anchorAddress?.boundId ?? null) selectSoleAddress() } else if (region.id !== regionId) { void confirmRegionSwitch(region, queryClient, anchorAddress?.boundId ?? null).then( selectSoleAddress ) } else if (anchorAddress?.boundId != null && anchorAddress.boundId !== boundId) { setRegion(region, anchorAddress.boundId) selectSoleAddress() } else { selectSoleAddress() } } return } // Location is in another serviceable region -> ask the user to choose. if (regionId != null) clearRegion() return } // No default or sole address: derive the region from the location as before. if (resolved?.region) { if (regionId == null) { // First region of this launch — adopt it without clearing the cart. setRegion(resolved.region, resolved.bound?.id ?? null) } else if (resolved.region.id !== regionId) { void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null) } else if (resolved.bound && resolved.bound.id !== boundId) { setRegion(resolved.region, resolved.bound.id) } } }, [ hydrated, startupResolved, resolution.data, resolution.isFetched, resolution.isError, locationStatus, regionId, boundId, setRegion, clearRegion, queryClient, hasAuthContext, isAuthenticated, isAuthLoading, cacheSnapshot.ready, cacheSnapshot.addresses, defaultAddressQuery.isFetched, defaultAddressQuery.isError, addressesQuery.isFetched, addressesQuery.isError, defaultAddress, soleAddress, regions, regionDataSignature, ]) // Reconcile the cached view with the live responses. The launch decision is // one-shot, so if it ran on the persisted snapshot we re-arm it once when the // background fetch shows different addresses/regions. This never fires for a // normal (cache-less) launch: the decision already waited for live data. useEffect(() => { if (!startupResolved) return const baseline = cacheBaselineRef.current if (!baseline) return const regionsLive = regionsQuery.dataUpdatedAt > 0 || regionsQuery.isError const addressesLive = !isAuthenticated || addressesQuery.dataUpdatedAt > 0 || addressesQuery.isError if (!regionsLive || !addressesLive) return cacheBaselineRef.current = null const baselineRegionsSignature = JSON.stringify( (baseline.regions ?? []).map((region) => [ region.id, region.name, region.description, region.effectiveBoundId, ]) ) const baselineAddressesSignature = JSON.stringify( (baseline.addresses?.data ?? []).map((address) => [ address.id, address.regionId, address.boundId, address.isDefault, ]) ) const liveRegionsSignature = JSON.stringify( (regions ?? []).map((region) => [ region.id, region.name, region.description, region.effectiveBoundId, ]) ) const liveAddressesSignature = JSON.stringify( (addresses ?? []).map((address) => [ address.id, address.regionId, address.boundId, address.isDefault, ]) ) const regionsChanged = baseline.regions != null && liveRegionsSignature !== baselineRegionsSignature const addressesChanged = baseline.addresses != null && liveAddressesSignature !== baselineAddressesSignature if (!regionsChanged && !addressesChanged) return // Allow the re-run to apply the live anchor even though a region is already // selected from cache. Only `startupLaunchRegionId === regionId` makes the // decision treat the current region as launch state rather than a manual pick. startupLaunchRegionId = regionId startupCheckDone = false setStartupResolved(false) }, [ startupResolved, regionsQuery.dataUpdatedAt, regionsQuery.isError, addressesQuery.dataUpdatedAt, addressesQuery.isError, isAuthenticated, regionId, regions, addresses, ]) // Sole-address safety net. The launch decision above runs once per app launch // (`startupResolved`/`startupCheckDone`), but the address list can arrive // later — e.g. the user was signed out when the gate first settled and logged // in from the address chooser. In that case the one-shot decision can no // longer adopt the address, so keep watching for the sole address here. useEffect(() => { if (!hydrated || isAuthLoading) return if (!isAuthenticated || regionId != null) return if (!soleAddress || soleAddress.regionId == null || !regions) return const region = regions.find((candidate) => candidate.id === soleAddress.regionId) ?? null if (!region) return setRegion(region, soleAddress.boundId ?? null) useAddressStore.getState().setSelectedAddressId(soleAddress.id) }, [hydrated, isAuthLoading, isAuthenticated, regionId, soleAddress, regions, setRegion]) // Safety net: a hanging resolve must not strand the first-run spinner. useEffect(() => { if (!hydrated || startupResolved || !shouldResolve) return const timer = setTimeout(() => { startupCheckDone = true setStartupResolved(true) }, RESOLVE_TIMEOUT_MS) return () => clearTimeout(timer) }, [hydrated, startupResolved, shouldResolve]) const isResolvingRegion = regionId == null && !startupResolved return { region, regionId, boundId, bound: resolution.data?.bound ?? null, regionGeneration, hydrated, coords, locationStatus, isResolvingRegion, setRegion, clearRegion, refreshLocation: () => { // Manual re-check: re-arm the launch check so a differing region switches. startupCheckDone = false startupLaunchRegionId = regionId setStartupResolved(false) void refreshTracking() }, } }