import { useState, useCallback } from 'react'; interface GeoState { loading: boolean; error: string | null; } /** * Hook to imperatively request the user's current GPS position. * Returns a `locate(onSuccess)` callback to trigger the permission prompt. */ export function useGeolocation() { const [state, setState] = useState({ loading: false, error: null }); const locate = useCallback((onSuccess: (lat: number, lng: number) => void) => { if (!navigator.geolocation) { setState({ loading: false, error: 'Geolocation is not supported by your browser.' }); return; } setState({ loading: true, error: null }); navigator.geolocation.getCurrentPosition( ({ coords }) => { setState({ loading: false, error: null }); onSuccess(coords.latitude, coords.longitude); }, (err) => { let message = 'Unable to get location.'; if (err.code === err.PERMISSION_DENIED) { message = 'Location permission denied. Please enable it in browser settings.'; } else if (err.code === err.POSITION_UNAVAILABLE) { message = 'Location unavailable. Try again or place the pin manually.'; } else if (err.code === err.TIMEOUT) { message = 'Location request timed out. Try again.'; } setState({ loading: false, error: message }); }, { enableHighAccuracy: true, timeout: 12_000, maximumAge: 0 } ); }, []); const clearError = useCallback(() => { setState((s) => ({ ...s, error: null })); }, []); return { ...state, locate, clearError }; }