/**
 * Loads the Google Maps JavaScript API once per page load and shares it between map pages. The
 * key comes from business settings (GOOGLE_MAP_API), passed to the page as a prop. Places and
 * geometry are always requested so a later page never finds them missing.
 */
let loading: Promise<typeof google> | null = null;

export function loadGoogleMaps(key: string | null): Promise<typeof google> {
    if (window.google?.maps?.Map) {
        return Promise.resolve(window.google);
    }
    if (loading) {
        return loading;
    }
    if (!key) {
        return Promise.reject(new Error('The Google Maps API key is not set in business settings.'));
    }

    loading = new Promise((resolve, reject) => {
        const callback = `__googleMapsReady${Date.now()}`;
        (window as unknown as Record<string, () => void>)[callback] = () => resolve(window.google);

        const script = document.createElement('script');
        script.src = `https://maps.googleapis.com/maps/api/js?${new URLSearchParams({ key, libraries: 'places,geometry', callback })}`;
        script.async = true;
        script.onerror = () => {
            loading = null;
            reject(new Error('Google Maps could not be loaded.'));
        };
        document.head.appendChild(script);
    });

    return loading;
}

export type LatLngTuple = [number, number];

export function toLatLng([lat, lng]: LatLngTuple): google.maps.LatLngLiteral {
    return { lat, lng };
}
