/**
 * Picks the map adapter for the configured provider and reports when its SDK is
 * ready on the page. Keeps the widgets provider-agnostic.
 */
const providerLoaders = {
	google: () => import( /* webpackChunkName: "cliq-map-google" */ './GoogleProvider' ),
	leaflet: () => import( /* webpackChunkName: "cliq-map-leaflet" */ './LeafletProvider' ),
};

const providerModules = new Map();

export const loadProvider = ( provider ) => {
	const key = provider === 'google' ? 'google' : 'leaflet';
	if ( ! providerModules.has( key ) ) {
		providerModules.set( key, providerLoaders[ key ]() );
	}
	return providerModules.get( key );
};

// Google's `loading=async` bootstrap defines `google.maps` BEFORE the library
// classes exist, so readiness must check for the Map constructor itself — an
// SSR-booted page reaches init before the SDK finishes and would crash on
// `new google.maps.Map` otherwise (the widget polls until ready).
export const isProviderReady = ( provider ) =>
	provider === 'google'
		? !! ( window.google && window.google.maps && window.google.maps.Map )
		: !! window.L;

export const createProvider = async ( provider, el, opts ) => {
	const key = provider === 'google' ? 'google' : 'leaflet';
	const module = await loadProvider( key );
	const Provider = key === 'google' ? module.GoogleProvider : module.LeafletProvider;
	return new Provider( el, opts );
};
