---
import "../../styles/map-google.css";

const {
    apiKey,
    lat,
    lon,
    zoom = 12,
    title = "",
    description = "",
    showMarker = false,
    mode = "full",
    mapStyleId = "8e0a97af9476f2d3"  
} = Astro.props;

const domId = `fuz-map-${Math.random().toString(36).slice(2)}`;
---

<div
    id={domId}
    class={
        mode === "full"
            ? "fuz-map--full"
            : mode === "contact"
                ? "fuz-map--contact"
                : "fuz-map--card"
    }
    data-lat={lat}
    data-lon={lon}
    data-zoom={zoom}
    data-title={title}
    data-desc={description}
    data-showmarker={showMarker}
></div>

<script is:inline define:vars={{ apiKey, domId, mapStyleId }}>

(function () {
    async function loadGoogleMaps(apiKey) {
        if (window.google?.maps?.importLibrary) return;

        if (!window._GOOGLE_MAPS_LOADING) {
            window._GOOGLE_MAPS_LOADING = new Promise((resolve, reject) => {
                const script = document.createElement("script");
                script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&loading=async&v=weekly`;
                script.async = true;
                script.defer = true;
                script.onerror = () => reject("Google Maps API failed to load");
                
                // Czekamy na google.maps.importLibrary
                script.onload = () => {
                    const checkReady = () => {
                        if (window.google?.maps?.importLibrary) {
                            resolve();
                        } else {
                            setTimeout(checkReady, 50);
                        }
                    };
                    checkReady();
                };
                
                document.head.appendChild(script);
            });
        }

        return window._GOOGLE_MAPS_LOADING;
    }

    async function initMap() {
        const el = document.getElementById(domId);
        if (!el) return;

        try {
            await loadGoogleMaps(apiKey);

            const { Map } = await google.maps.importLibrary("maps");
            const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

            const lat = Number(el.dataset.lat);
            const lon = Number(el.dataset.lon);
            const zoom = Number(el.dataset.zoom);
            const title = el.dataset.title || "";
            const desc = el.dataset.desc || "";
            const showMarker = el.dataset.showmarker === "true";

            const map = new Map(el, {
                center: { lat, lng: lon },
                zoom,
                mapId: mapStyleId,
                mapTypeControl: false,
                fullscreenControl: false,
                streetViewControl: false,
                scrollwheel: false,
                zoomControl: true,
            });

            window.fuzMaps = window.fuzMaps || {};
            window.fuzMaps[domId] = map;

            if (showMarker) {
                const marker = new AdvancedMarkerElement({
                    map,
                    position: { lat, lng: lon }
                });

                if (title || desc) {
                    const { InfoWindow } = await google.maps.importLibrary("maps");
                    const info = new InfoWindow({
                        content: `
                            <div class="f-info-window">
                              <div class="f-info-header">
                                <div class="f-info-city">${title}</div>
                                <div class="f-info-street">${desc}</div>
                              </div>   
                            </div>
                        `
                    });

                    info.open({ map, anchor: marker });
                }
            }
        } catch (error) {
            console.error("Error initializing map:", error);
        }
    }

    document.addEventListener("DOMContentLoaded", initMap);

})();
</script>