import React, { useEffect, useState } from 'react' import { View, Modal } from 'react-native' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' import AddressForm from '@/src/components/AddressForm' import { useLocationStore } from '@/src/store/locationStore' // How often to re-check the device location while we still have no fix. const LOCATION_POLL_MS = 3000 interface CartAddressGateProps { /** Called once the first address has been saved. */ onDone: () => void /** Back out of the cart. */ onBack: () => void } /** * Shown on the cart page when the browsing region/bound is known (from the * device location) but the signed-in user has no delivery address yet. The * first address they save becomes their default, and we then show the cart. */ const CartAddressGate: React.FC = ({ onDone, onBack }) => { const coords = useLocationStore((state) => state.coords) const probeLocation = useLocationStore((state) => state.probe) const refreshPosition = useLocationStore((state) => state.refresh) const [mode, setMode] = useState<'none' | 'current' | 'other'>('none') // The store takes its fix once per app launch, so a user who turns the location // on after landing here would never see the "current location" option enable. // While we have no fix, keep checking and take one as soon as the location is // usable. Polling stops as soon as coords arrive. useEffect(() => { if (coords) return let cancelled = false const check = async () => { // A fix is already in flight; don't stack another one on top. if (useLocationStore.getState().status === 'locating') return const usable = await probeLocation() if (cancelled || !usable) return void refreshPosition() } const timer = setInterval(() => void check(), LOCATION_POLL_MS) return () => { cancelled = true clearInterval(timer) } }, [coords, probeLocation, refreshPosition]) return ( Add Delivery Address Where should we deliver? You don’t have a delivery address yet. Add one to continue. setMode('current')} style={tw`bg-white border border-gray-200 rounded-2xl p-4 mb-3 shadow-sm ${!coords ? 'opacity-50' : ''}`} > Address of current Location {coords ? `Use your current location (${coords.latitude.toFixed(5)}, ${coords.longitude.toFixed(5)})` : 'Turn on location to use this option'} setMode('other')} style={tw`bg-white border border-gray-200 rounded-2xl p-4 shadow-sm`} > Choose another location Pick a point on the map setMode('none')} > { setMode('none') onDone() }} /> ) } export default CartAddressGate