/** Lazily loaded Google Directions workflow. */
export const showGoogleDirections = ( provider, origin, dest, opts = {} ) => {
	if ( ! provider.map || ! origin || ! dest || ! provider.g?.maps?.DirectionsService ) {
		return Promise.resolve( false );
	}
	if ( ! provider.directionsService ) {
		provider.directionsService = new provider.g.maps.DirectionsService();
		provider.directionsRenderer = new provider.g.maps.DirectionsRenderer( {
			suppressMarkers: false,
			preserveViewport: false,
		} );
	}
	provider.directionsRenderer.setMap( provider.map );
	provider.directionsRenderer.setPanel( opts.panel || null );
	return new Promise( ( resolve ) => {
		provider.directionsService.route(
			{
				origin: { lat: Number( origin.lat ), lng: Number( origin.lng ) },
				destination: { lat: Number( dest.lat ), lng: Number( dest.lng ) },
				travelMode: provider.g.maps.TravelMode.DRIVING,
			},
			( result, status ) => {
				if ( status !== 'OK' || ! result ) {
					resolve( false );
					return;
				}
				provider.directionsRenderer.setDirections( result );
				const leg = result.routes?.[ 0 ]?.legs?.[ 0 ] || {};
				resolve( {
					distance: leg.distance?.text || '',
					duration: leg.duration?.text || '',
					origin: leg.start_address || '',
				} );
			}
		);
	} );
};
