import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useContext, useEffect, useState } from 'react';
import Tooltip from '../Tooltip';
import { useElement, useI18n } from '../../hooks';
import Icon, { registerIcon } from '../Icon';
import * as locationIcon from '../Icon/icons/location.icon';
import Button from '../Button';
import MapsContext from './MapsContext';
import { getNavigatorPosition, getAddress, loadMapsAPI } from './utils';
registerIcon(locationIcon);
const CurrentLocationButton = ({ onResolve, onError }) => {
    const t = useI18n();
    const { name, ...providerOpts } = useContext(MapsContext);
    const [currentLocationDisabled, setCurrentLocationDisabled] = useState(false);
    const [busy, setBusy] = useState(false);
    const [el, setEl] = useElement();
    const getCurrentLocation = useCallback(() => {
        setBusy(true);
        Promise.all([getNavigatorPosition(), loadMapsAPI(name, providerOpts)])
            .catch(error => {
            setCurrentLocationDisabled(true);
            throw error;
        })
            .then(([navigatorPosition]) => getAddress(navigatorPosition))
            .then(address => {
            onResolve?.(address);
        })
            .catch(error => onError?.(error))
            .finally(() => setBusy(false));
    }, [onResolve, onError]);
    useEffect(() => {
        navigator.permissions?.query({ name: 'geolocation' }).then(result => {
            if (result.state === 'denied') {
                setCurrentLocationDisabled(true);
            }
        });
    }, []);
    return (_jsxs(_Fragment, { children: [_jsx(Button, { ref: setEl, variant: 'simple', icon: true, onClick: getCurrentLocation, "aria-label": t('my_current_location_button_a11y'), disabled: currentLocationDisabled, loading: busy, children: _jsx(Icon, { name: 'location' }) }), el && currentLocationDisabled && (_jsx(Tooltip, { shown: true, target: el, children: t('allow_location_permissions_text') }))] }));
};
export default CurrentLocationButton;
//# sourceMappingURL=CurrentLocationButton.js.map