import { useCallback, useEffect, useState } from 'react' import { IconBack, IconPin, IconCompass, IconChevronRight, IconSun } from '../components/Icons' import { latText, lonText } from '../lib/format' import { startCamera, startOrientation } from '../lib/camera' import { errText } from '../lib/wasm' import { EMBEDDED, nativeCall } from '../lib/files' import { t } from '../i18n' const canLocate = () => EMBEDDED || !!navigator.geolocation const located = (latDeg, lonDeg, elevM, accuracyM) => ({ status: 'ok', error: '', loc: { latDeg, lonDeg, elevM: typeof elevM === 'number' ? elevM : null, accuracyM }, }) const unavailable = () => ({ status: 'error', loc: null, error: t('setup.geoUnavailable') }) /** One fix → the hook's state ({status, loc, error}). */ async function fetchLocation() { if (EMBEDDED) { // iOS shell: Core Location with the app's own permission (the WebView // would ask "localhost …" again on every launch). Android answers // {unsupported}: its WebView geolocation is already granted for good. const r = await nativeCall('getLocation') if (r && typeof r.lat === 'number') return located(r.lat, r.lon, r.alt, r.accuracy) if (r && r.error) return unavailable() } if (!navigator.geolocation) return { status: 'error', loc: null, error: t('setup.noGeo') } return new Promise((resolve) => navigator.geolocation.getCurrentPosition( (p) => resolve(located(p.coords.latitude, p.coords.longitude, p.coords.altitude, p.coords.accuracy)), () => resolve(unavailable()), { enableHighAccuracy: true, timeout: 20000, maximumAge: 60000 }, )) } function useLocation() { const [state, setState] = useState(() => (canLocate() ? { status: 'locating', loc: null, error: '' } : { status: 'error', loc: null, error: t('setup.noGeo') })) const locate = useCallback(() => { fetchLocation().then(setState) }, []) useEffect(() => { locate() }, [locate]) const refresh = () => { if (!canLocate()) return setState((s) => ({ ...s, status: 'locating', error: '' })) locate() } return [state, refresh] } export default function Setup({ suggestedName, onBack, onStart }) { const [name, setName] = useState(suggestedName) const [location, refresh] = useLocation() const [starting, setStarting] = useState(false) const [error, setError] = useState('') const start = async () => { setError('') setStarting(true) // Sensors first and synchronously from the tap: iOS only asks inside a gesture. const ori = startOrientation() try { await ori } catch (e) { setStarting(false) setError(t('setup.sensorsError', { error: errText(e) })) return } try { await startCamera() } catch (e) { setStarting(false) setError(t('setup.cameraError', { error: errText(e) })) return } onStart({ name: name.trim() || suggestedName, location: location.loc }) } const loc = location.loc return (