import { useEffect, useMemo, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import type { RegionSummary, RegionBoundSummary } from '@packages/shared' import { useRegionStore } from '@/src/store/regionStore' import { useLocationStore } from '@/src/store/locationStore' import { trpc } from '@/src/trpc-client' import { confirmRegionSwitch } from '@/src/lib/region-switch' 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. */ 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 auth = useAuthOptional() const isAuthenticated = auth?.isAuthenticated ?? false const isAuthLoading = auth?.isLoading ?? false 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) // 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, }) const defaultAddress = defaultAddressQuery.data?.data ?? 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 ?? null // 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. // Without a default address we keep the previous behaviour (use the resolved // region, else let the user pick). useEffect(() => { if (!hydrated || startupResolved) 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 // Signed-in users: wait for the default address (+ regions) so the decision // is anchored correctly before we settle. if (isAuthenticated) { if (defaultAddressQuery.isLoading) return if (defaultAddress?.regionId != null && !regions) return } 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 defaultRegionId = isAuthenticated ? defaultAddress?.regionId ?? null : null if (defaultRegionId != null) { const inDefaultRegion = resolved?.region?.id === defaultRegionId // No serviceable region found -> treat like a disabled location. const noServiceableRegion = resolved == null if (inDefaultRegion || noServiceableRegion) { const region = regions?.find((candidate) => candidate.id === defaultRegionId) ?? null if (region) { if (regionId == null) { // First region of this launch — adopt it without clearing the cart. setRegion(region, defaultAddress?.boundId ?? null) } else if (region.id !== regionId) { void confirmRegionSwitch(region, queryClient, defaultAddress?.boundId ?? null) } else if (defaultAddress?.boundId != null && defaultAddress.boundId !== boundId) { setRegion(region, defaultAddress.boundId) } } return } // Location is in another serviceable region -> ask the user to choose. if (regionId != null) clearRegion() return } // No default 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, isAuthenticated, isAuthLoading, defaultAddressQuery.isLoading, defaultAddress, regions, ]) // 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() }, } }