import React, { useState, useEffect, useRef } from 'react'; import * as Location from 'expo-location'; import * as Linking from 'expo-linking'; import { View, ActivityIndicator, AppState, Platform } from 'react-native'; import { MyText, MyTouchableOpacity, tw } from 'common-ui'; import type { ReactParentComponent } from '@packages/shared'; import { trpc } from '../src/trpc-client'; import { useRegion } from '../src/contexts/RegionContext'; type GateReason = 'denied' | 'servicesOff' | 'unserved' | 'error'; const RegionGate: React.FC = ({ children }) => { const { regionId, regionName, isLoading: regionLoading, setRegion } = useRegion(); const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null); const [denied, setDenied] = useState(false); const [servicesOff, setServicesOff] = useState(false); const [detectError, setDetectError] = useState(false); const [detecting, setDetecting] = useState(true); const [showPicker, setShowPicker] = useState(false); const [picked, setPicked] = useState(false); const [attempt, setAttempt] = useState(0); const passedRef = useRef(false); const appState = useRef(AppState.currentState); const runDetection = async () => { if (passedRef.current) return; setDetecting(true); setDenied(false); setServicesOff(false); setDetectError(false); setCoords(null); try { const { status } = await Location.requestForegroundPermissionsAsync(); if (passedRef.current) return; if (status !== 'granted') { setDenied(true); return; } const servicesEnabled = await Location.hasServicesEnabledAsync(); if (passedRef.current) return; if (!servicesEnabled) { setServicesOff(true); return; } const location = await Location.getCurrentPositionAsync({}); if (passedRef.current) return; setCoords({ lat: location.coords.latitude, lng: location.coords.longitude }); } catch (error) { if (!passedRef.current) setDetectError(true); } finally { if (!passedRef.current) setDetecting(false); } }; useEffect(() => { void runDetection(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [attempt]); // Re-check when returning from OS/app Settings. useEffect(() => { const sub = AppState.addEventListener('change', (next) => { if (appState.current.match(/inactive|background/) && next === 'active') { setAttempt((a) => a + 1); } appState.current = next; }); return () => sub.remove(); }, []); const resolveQuery = trpc.common.resolveRegionForLocation.useQuery( { lat: coords?.lat ?? 0, lng: coords?.lng ?? 0 }, { enabled: !!coords, retry: false, refetchOnWindowFocus: false, staleTime: Infinity } ); const resolved = resolveQuery.data; const resolveFailed = resolveQuery.isError; useEffect(() => { if (resolved?.regionId != null) { passedRef.current = true; void setRegion(resolved.regionId, resolved.regionName ?? '', resolved.boundId, resolved.boundName); } }, [resolved, setRegion]); const { data: regionsData, isLoading: regionsLoading } = trpc.common.getRegions.useQuery( undefined, { staleTime: Infinity } ); const handlePick = (id: number, name: string) => { passedRef.current = true; setPicked(true); void setRegion(id, name); }; const handlePrimaryAction = async () => { if (servicesOff && Platform.OS === 'android') { try { await Location.enableNetworkProviderAsync(); } catch { // User dismissed the system dialog; fall through to re-check. } setAttempt((a) => a + 1); return; } await Linking.openSettings(); }; // GPS resolved to a served region, or the user picked/continued manually. if (resolved?.regionId != null || picked) { return <>{children}; } if (detecting || regionLoading || (!!coords && !resolved && !resolveFailed)) { return ( Detecting your region… ); } const detectionBlocked = denied || servicesOff; const reason: GateReason = denied ? 'denied' : servicesOff ? 'servicesOff' : resolveFailed || detectError ? 'error' : 'unserved'; // Hard failure (permission or location switch): message + action, picker on demand. if ((detectionBlocked || showPicker) && reason !== 'unserved') { if (!showPicker) { const subheading = denied ? 'We need location permission to auto-detect your region. Grant access in Settings, or choose your region manually.' : 'Your location is turned off. Turn it on to auto-detect your region, or choose your region manually.'; return ( Unable to obtain location {subheading} {servicesOff && Platform.OS === 'android' ? 'Turn on location' : 'Open Settings'} setShowPicker(true)} > Choose region manually {regionId != null && ( handlePick(regionId, regionName ?? '')} > Continue with {regionName ?? 'saved region'} )} ); } } // Region picker: unserved GPS, resolution failure, or manual choice. const pickerTitle = reason === 'unserved' ? 'Outside service area' : 'Choose your region'; const pickerMessage = reason === 'unserved' ? 'Your current location is outside the areas we serve. You can still continue by picking a region below.' : reason === 'error' ? 'We could not detect your region. Pick one below to continue.' : 'Pick your region below to continue.'; const regions = regionsData?.regions ?? []; return ( {pickerTitle} {pickerMessage} {regionsLoading ? ( ) : ( regions.map((region) => ( handlePick(region.id, region.name)} > {region.name} {!!region.description && ( {region.description} )} )) )} ); }; export default RegionGate;