<div x-data="googleMap()" x-init="init()" class="flex gap-4 h-full">
    <div id="DEMO_MAP_ID" class="w-full sm:h-full" :class="$store.locator.filteredDistanceStores.length !== 0 ? 'max-sm:aspect-square' : 'max-sm:aspect-[2/3]' "></div>
</div>

<script>
    function googleMap() {
        let mapsLib = null;
        let markerLib = null;
        let mapInstance = null;
        return {
            mapId: "DEMO_MAP_ID",
            markers: [],
            selectedMarker: null,
            markerCluster: null,
            CustomOverlayWindow: null,
            infoWindow: null,
            async init() {
                try {
                    await this.loadLibraries();
                    await this.initializeMapAndMarkers();
                    this.watchStores();
                } catch (error) {
                    console.error('Erreur init:', error);
                }
            },
            initializeMapAndMarkers() {
                this.initMap();
                this.updateMarkersFromStore();
            },
            watchStores() {
                this.$watch('$store.locator.allStores', () => {
                    this.updateMarkersFromStore();
                });
                this.$store.locator.onSelectStore = (store) => {
                    this.showStorePopup(store);
                };
            },
            async loadLibraries() {
                try {
                    const {
                        maps,
                        marker
                    } = await this.setupGoogleLibraries();
                    mapsLib = maps;
                    markerLib = marker;
                } catch (error) {
                    console.error('Erreur lors du chargement des bibliothèques:', error);
                    throw error;
                }
            },
            async setupGoogleLibraries() {
                const [maps, marker] = await Promise.all([
                    google.maps.importLibrary("maps"),
                    google.maps.importLibrary("marker"),
                ]);
                this.CustomOverlayWindow = class extends google.maps.OverlayView {
                    constructor(position, contentHTML, map) {
                        super();
                        this.position = position;
                        this.containerDiv = document.createElement("div");
                        this.containerDiv.className = "absolute z-[999] pointer-events-auto";
                        this.containerDiv.appendChild(contentHTML);
                        const arrow = document.createElement("div");
                        arrow.className = `
                            absolute
                            top-1/2 left-[-7px] -translate-y-1/2
                            border-y-[7px] border-y-transparent
                            border-r-[7px] border-r-white
                        `;
                        this.containerDiv.appendChild(arrow);
                        this.setMap(map);
                    }
                    onAdd() {
                        this.getPanes().floatPane.appendChild(this.containerDiv);
                    }
                    draw() {
                        const projection = this.getProjection();
                        const point = projection.fromLatLngToDivPixel(this.position);
                        if (point) {
                            const offsetX = 24;
                            const offsetY = -this.containerDiv.offsetHeight / 2;
                            this.containerDiv.style.left = `${point.x + offsetX}px`;
                            this.containerDiv.style.top = `${point.y + offsetY}px`;
                        }
                    }
                    onRemove() {
                        this.containerDiv?.remove();
                    }
                    close() {
                        this.setMap(null);
                    }
                };
                return {
                    maps,
                    marker
                };
            },
            async initMap() {
                if (!mapsLib) {
                    throw new Error('Les bibliothèques Google Maps ne sont pas chargées');
                }
                try {
                    const urlParams = new URLSearchParams(window.location.search);
                    const lat = urlParams.get('lat') || 6.603354;
                    const lng = urlParams.get('lng') || 1.888334;
                    const validation = this.$store.locator.validateCoordinates(lat, lng);
                    const coordinates = validation.isValid ?
                        validation.coordinates : {
                            lat: 46.603354,
                            lng: 1.888334
                        };
                    mapInstance = new google.maps.Map(document.getElementById(this.mapId), {
                        center: coordinates,
                        zoom: 4,
                        mapId: this.mapId,
                        mapTypeControl: false,
                        fullscreenControl: false,
                        streetViewControl: false,
                        zoomControl: !this.$store.screen.isMobile
                    });
                    this.$store.locator.mapInstance = mapInstance;
                    this.$store.locator.updateDistances();
                    mapInstance.addListener('idle', () => {
                        this.$store.locator.updateDistances();
                        this.updateUrlParams();
                    });
                } catch (error) {
                    console.error('Erreur lors de l\'initialisation de la carte:', error);
                    throw error;
                }
            },
            updateUrlParams() {
                if (!mapInstance) return;
                try {
                    const center = mapInstance.getCenter();
                    const newUrl = new URL(window.location.href);
                    const validation = this.$store.locator.validateCoordinates(
                        center.lat(),
                        center.lng()
                    );
                    if (validation.isValid) {
                        newUrl.searchParams.set('lat', validation.coordinates.lat.toFixed(6));
                        newUrl.searchParams.set('lng', validation.coordinates.lng.toFixed(6));
                        window.history.replaceState({}, '', newUrl.toString());
                    }
                } catch (error) {
                    console.error('Erreur lors de la mise à jour des paramètres URL:', error);
                }
            },
            createMarkerElement(isSelected = false) {
                const container = document.createElement('div');
                container.className = `relative group`;
                const baseClass = isSelected ?
                    'text-black hover:text-neutral-900' :
                    'text-brand-500 hover:text-brand-600';
                const detailPathClass = isSelected ?
                    'fill-white' :
                    'fill-black group-hover:fill-white';
                container.innerHTML = `
                    <svg width="41" height="49" viewBox="0 0 41 49" fill="none" xmlns="http://www.w3.org/2000/svg" class="transition-colors duration-200 ${baseClass}">
                        <path d="M21.5709 48.2273L21.5709 48.2274L21.5759 48.2246L21.6419 48.1875L21.6438 48.1864C21.6843 48.1634 21.7407 48.1311 21.8121 48.0894L21.56 47.6576L21.8121 48.0894C21.9549 48.006 22.1575 47.8852 22.4115 47.7276C22.9191 47.4126 23.6333 46.9495 24.4855 46.3428C26.186 45.132 28.4554 43.3354 30.7311 40.9871C35.2546 36.3193 40 29.2591 40 20.1495C40 9.30109 31.2732 0.5 20.5 0.5C9.72676 0.5 1 9.30109 1 20.1495C1 29.2591 5.74544 36.3193 10.2689 40.9871C12.5446 43.3354 14.814 45.132 16.5145 46.3428C17.3667 46.9495 18.0809 47.4126 18.5885 47.7276C18.8425 47.8852 19.0451 48.006 19.1879 48.0894L19.44 47.6576L19.1879 48.0894C19.2593 48.1311 19.3157 48.1634 19.3562 48.1864L19.358 48.1874L19.4223 48.2236L19.4252 48.2252C20.0904 48.5932 20.9089 48.5892 21.5709 48.2273Z" fill="currentColor" stroke="white" stroke-linejoin="round"/>
                        <path class="${detailPathClass}" fill-rule="evenodd" clip-rule="evenodd" d="M28.7676 24.4986H13.331L13.3631 24.2493C13.6217 22.2282 14.5391 20.5823 16.0902 19.3575C17.6352 18.1364 19.3937 17.5171 21.3176 17.5171C23.2957 17.5171 24.9873 18.1205 26.3448 19.3103C27.7007 20.5 28.5066 22.1623 28.7402 24.2526L28.7676 24.4986ZM21.3177 16.3559C18.779 16.3559 16.5538 17.2136 14.7033 18.9055C12.8579 20.5945 11.9218 22.8317 11.9218 25.5549C11.9218 28.2532 12.8448 30.4591 14.6654 32.1118C16.4887 33.7672 18.6502 34.6064 21.0888 34.6064C23.1885 34.6064 25.0014 34.1216 26.4777 33.1652C27.8869 32.2525 28.9513 30.9261 29.6455 29.2188L28.4592 28.9541C27.1369 31.9591 24.6588 33.4816 21.0888 33.4816C19.0591 33.4816 17.2387 32.7608 15.6782 31.3391C14.1162 29.9147 13.3108 28.0068 13.2844 25.6664L13.2819 25.4418H30.1426V25.007C30.0432 22.4551 29.1634 20.349 27.5265 18.7549C25.8926 17.1631 23.8038 16.3559 21.3177 16.3559Z"/>
                        <path class="${detailPathClass}" fill-rule="evenodd" clip-rule="evenodd" d="M23.7425 10.5L23.7384 10.6097C23.7105 11.4097 23.4413 12.0745 22.9371 12.585C22.403 13.1245 21.724 13.3984 20.9195 13.3984C20.1349 13.3984 19.467 13.1252 18.9334 12.5855C18.4282 12.0754 18.1584 11.4102 18.1305 10.6097L18.1271 10.5H16.9199L16.9226 10.6172C16.9521 11.7614 17.3271 12.6959 18.0383 13.396C18.7816 14.1286 19.7507 14.5 20.9195 14.5C22.0885 14.5 23.0573 14.1286 23.8008 13.396C24.5119 12.6964 24.8875 11.7617 24.917 10.6172L24.9199 10.5H23.7425Z"/>
                    </svg>
                `;
                return container;
            },
            updateMarkersFromStore() {
                if (!markerLib || !mapInstance) return;
                try {
                    this.clearMarkers();
                    const validStores = this.$store.locator.allStores.filter(store => {
                        const validation = this.$store.locator.validateCoordinates(store.lat, store.lng);
                        if (!validation.isValid) {
                            console.warn(`Marqueur ignoré pour le store ${store.id || 'Unknown'}: ${validation.error}`);
                            return false;
                        }
                        return true;
                    });
                    this.markers = validStores.map(store => {
                        const validation = this.$store.locator.validateCoordinates(store.lat, store.lng);
                        const position = validation.coordinates;
                        const marker = new markerLib.AdvancedMarkerElement({
                            position,
                            content: this.createMarkerElement(),
                            map: mapInstance
                        });
                        this.addMarkerEvents(marker, store);
                        return marker;
                    });
                    this.createMarkerCluster(this.markers);
                } catch (error) {
                    console.error('Erreur lors de la mise à jour des marqueurs:', error);
                }
            },
            clearMarkers() {
                try {
                    if (this.markerCluster) {
                        this.markerCluster.setMap(null);
                    }
                    this.markers.forEach(marker => marker.setMap(null));
                    this.markers = [];
                } catch (error) {
                    console.error('Erreur lors du nettoyage des marqueurs:', error);
                }
            },
            createMarkerCluster(markersToCluster) {
                if (!mapInstance || !markersToCluster.length) return;
                try {
                    this.markerCluster = new markerClusterer.MarkerClusterer({
                        markers: markersToCluster,
                        map: mapInstance,
                        ignoreHidden: true,
                        algorithm: new markerClusterer.SuperClusterAlgorithm({
                            radius: 150,
                            maxZoom: 12
                        }),
                        renderer: {
                            render: ({
                                count,
                                position
                            }) => {
                                let size = 56;
                                if (count < 10) size = 40;
                                else if (count >= 100) size = 72;
                                const container = document.createElement('div');
                                container.className = `
                                    flex items-center justify-center
                                    rounded-full
                                    text-black text-body-lg font-bold
                                    ring-2 ring-brand-500/32
                                    bg-brand-500
                                    transition-all duration-200
                                    hover:ring-[6px] hover:bg-brand-600 hover:text-white
                                `;
                                container.style.width = `${size}px`;
                                container.style.height = `${size}px`;
                                container.textContent = count;
                                return new markerLib.AdvancedMarkerElement({
                                    position,
                                    content: container
                                });
                            }
                        }
                    });
                } catch (error) {
                    console.error('Erreur lors de la création du cluster de marqueurs:', error);
                }
            },
            showStorePopup(store) {
                const content = this.createInfoWindowContent(store);
                const closeBtn = content.querySelector('[data-close]');
                if (this.$store.screen.isMobile) {
                    const layer = document.createElement('div');
                    layer.className = "fixed inset-0 z-[9999] bg-white p-4 overflow-auto";
                    closeBtn?.addEventListener('click', () => {
                        layer.remove();
                        this.closeInfoWindow();
                    });
                    layer.appendChild(content);
                    document.body.appendChild(layer);
                } else {
                    const position = new google.maps.LatLng(store.lat, store.lng);
                    this.$store.locator.setMapCenter(store.lat, store.lng);
                    closeBtn?.addEventListener('click', () => this.closeInfoWindow());
                    this.infoWindow = new this.CustomOverlayWindow(position, content, this.$store.locator.mapInstance);
                }
            },
            addMarkerEvents(marker, store) {
                marker.addListener('gmp-click', () => {
                    if (this.infoWindow) {
                        this.infoWindow.close();
                    }
                    if (this.selectedMarker) {
                        this.selectedMarker.setMap(null);
                    }
                    const selected = new markerLib.AdvancedMarkerElement({
                        position: {
                            lat: parseFloat(store.lat),
                            lng: parseFloat(store.lng)
                        },
                        content: this.createMarkerElement(true),
                        map: mapInstance
                    });
                    this.addMarkerEvents(selected, store);
                    this.selectedMarker = selected;
                    this.showStorePopup(store);
                });
            },
            createInfoWindowContent(store) {
                const div = document.createElement('div');
                div.className = "max-md:fixed max-md:inset-0 w-full h-full bg-white z-[9999]";
                div.innerHTML = `<div class="flex flex-col gap-3 cursor-default h-full bg-white md:shadow-32 md:w-screen-50 md:max-w-80 p-3" @click.outside="closeInfoWindow()">
    <div class="bg-brand-100 flex justify-between items-start gap-2 relative px-4 py-2">
        <div>
            <h3 class="text-click-sm text-black font-bold uppercase line-clamp-1">${store.name}</h3>
            <p class="text-click-xs leading-tight text-black/80">${store.address}<br>${store.city}</p>
        </div>
                <button
    type="button"
    
    data-close 
    
    aria-label="Label text"    class=" btn  btn-neutral  btn-outline  btn-size-sm btn-only-icon">
                        <svg class=" shrink-0"
                    width="24"
                            height="24"
                            stroke="currentColor"
                            stroke-width="1.5"
             viewBox="0 0 24 24"
             xmlns="http://www.w3.org/2000/svg"
     aria-hidden="true"
     
>
                        <path
                                        d="M6 18 18 6M6 6l12 12"
                                            stroke="currentColor"
                                                                stroke-width="1.5"
                                                                fill="none"
                                />
            
    </svg>                
                
    </button>
    </div>

    <div class="flex flex-col gap-3 text-click-xs px-4">
        <div class="flex items-center gap-2 font-bold">
            <svg class=" shrink-0"
                    width="16"
                            height="16"
                            stroke="currentColor"
                            stroke-width="1.5"
             viewBox="0 0 24 24"
             xmlns="http://www.w3.org/2000/svg"
     aria-hidden="true"
     
>
                        <path
                                        d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z"
                                            stroke="currentColor"
                                                                stroke-width="1.5"
                                                                fill="none"
                                />
            
    </svg>            ${store.phone
                ? `<a href="tel:${store.phone.replace(/\s+/g, '')}">${store.phone}</a>`
                : `<span>Téléphone non disponible</span>`
            }
        </div>

        <div class="flex flex-col gap-2">
            <h4 class="font-bold flex items-center gap-1">
                <svg class=" shrink-0"
                    width="16"
                            height="16"
                            stroke="currentColor"
                            stroke-width="1.5"
             viewBox="0 0 21 20"
             xmlns="http://www.w3.org/2000/svg"
     aria-hidden="true"
     
>
                        <path
                                        d="M10.5 5V10H14.25M18 10C18 14.1421 14.6421 17.5 10.5 17.5C6.35786 17.5 3 14.1421 3 10C3 5.85786 6.35786 2.5 10.5 2.5C14.6421 2.5 18 5.85786 18 10Z"
                                            stroke="currentColor"
                                                                stroke-width="1.5"
                                                                fill="none"
                                />
            
    </svg>                Horaires d’ouverture
            </h4>
            <div class="divide-y divide-black/08">
                ${Alpine.store('locator').days.map(day => {
                const value = (store[day.key] || '').trim();
                const segments = value.includes(',') ? value.split(',').map(s => s.trim()) : [value];
                const closed = segments[0].toLowerCase().includes("fermé");

                return `
                    <div class="flex justify-between py-1">
                        <span class="font-bold">${day.label}</span>
                        <span class="whitespace-nowrap">
                            ${segments.filter(Boolean).join('<br>') || 'Fermé'}
                        </span>
                    </div>
                `;
                }).join('')}
            </div>
        </div>

                <a href="https://www.google.com/maps/dir/?api=1&destination=${store.lat},${store.lng}"
    type="button"
    target="_blank" rel="noopenner noreferer"
    aria-label="Itinéraire (s'ouvre dans un nouvel onglet)"
     
    
        class="w-fit  btn  btn-dark  btn-outline  btn-size-sm btn-icons">
                            Itinéraire
    
                        <svg class=" shrink-0"
                    width="24"
                            height="24"
                            stroke="currentColor"
                            stroke-width="1.5"
             viewBox="0 0 20 21"
             xmlns="http://www.w3.org/2000/svg"
     aria-hidden="true"
     
>
                        <path
                                        d="M17.051 2.52738C17.2846 2.43058 17.5535 2.48403 17.7323 2.66281C17.911 2.84159 17.9645 3.11047 17.8677 3.34404L11.7202 18.1699C11.6147 18.4239 11.3557 18.5791 11.082 18.5522C10.8083 18.5254 10.5843 18.3228 10.5302 18.0532L9.1652 11.2299L2.34186 9.86488C2.07224 9.81076 1.86968 9.58677 1.84284 9.31308C1.81601 9.0394 1.97122 8.78033 2.2252 8.67488L17.051 2.52738Z"
                                            stroke="currentColor"
                                                                stroke-width="1.5"
                                                                fill="none"
                                />
            
    </svg>            
    </a>
    </div>
</div>`;
                return div;
            },
            closeInfoWindow() {
                this.infoWindow.close();
                this.selectedMarker.setMap(null);
                this.selectedMarker = null;
            }
        };
    }
</script>
<div
    x-data="googleMap()"
    x-init="init()"
    class="flex gap-4 h-full"
>
    <div id="{{ mapId }}" class="w-full sm:h-full" :class="$store.locator.filteredDistanceStores.length !== 0 ? 'max-sm:aspect-square' : 'max-sm:aspect-[2/3]' "></div>
</div>

<script>
	function googleMap() {
		let mapsLib = null;
		let markerLib = null;
		let mapInstance = null;

		return {
			mapId: "DEMO_MAP_ID",
			markers: [],
            selectedMarker: null,
			markerCluster: null,

			CustomOverlayWindow: null,
			infoWindow: null,

			async init() {
				try {
					await this.loadLibraries();
					await this.initializeMapAndMarkers();
					this.watchStores();
				} catch (error) {
					console.error('Erreur init:', error);
				}
			},

			initializeMapAndMarkers() {
                this.initMap();
                this.updateMarkersFromStore();
			},

			watchStores() {
				this.$watch('$store.locator.allStores', () => {
					this.updateMarkersFromStore();
				});
                this.$store.locator.onSelectStore = (store) => {
                    this.showStorePopup(store);
                };
			},

			async loadLibraries() {
				try {
					const {maps, marker} = await this.setupGoogleLibraries();
					mapsLib = maps;
					markerLib = marker;
				} catch (error) {
					console.error('Erreur lors du chargement des bibliothèques:', error);
					throw error;
				}
			},

			async setupGoogleLibraries() {
				const [maps, marker] = await Promise.all([
					google.maps.importLibrary("maps"),
					google.maps.importLibrary("marker"),
				]);

				this.CustomOverlayWindow = class extends google.maps.OverlayView {
					constructor(position, contentHTML, map) {
						super();
						this.position = position;
						this.containerDiv = document.createElement("div");
						this.containerDiv.className = "absolute z-[999] pointer-events-auto";
						this.containerDiv.appendChild(contentHTML);

                        const arrow = document.createElement("div");
                        arrow.className = `
                            absolute
                            top-1/2 left-[-7px] -translate-y-1/2
                            border-y-[7px] border-y-transparent
                            border-r-[7px] border-r-white
                        `;

                        this.containerDiv.appendChild(arrow);
						this.setMap(map);
					}

					onAdd() {
						this.getPanes().floatPane.appendChild(this.containerDiv);
					}

					draw() {
						const projection = this.getProjection();
						const point = projection.fromLatLngToDivPixel(this.position);
						if (point) {
                            const offsetX = 24;
                            const offsetY = -this.containerDiv.offsetHeight / 2;

                            this.containerDiv.style.left = `${point.x + offsetX}px`;
                            this.containerDiv.style.top = `${point.y + offsetY}px`;
						}
					}

					onRemove() {
						this.containerDiv?.remove();
					}

					close() {
						this.setMap(null);
					}
				};

				return {maps, marker};
			},

			async initMap() {
				if (!mapsLib) {
					throw new Error('Les bibliothèques Google Maps ne sont pas chargées');
				}

				try {
					const urlParams = new URLSearchParams(window.location.search);
					const lat = urlParams.get('lat') || 6.603354;
					const lng = urlParams.get('lng') || 1.888334;

					const validation = this.$store.locator.validateCoordinates(lat, lng);
					const coordinates = validation.isValid ?
						validation.coordinates :
						{lat: 46.603354, lng: 1.888334};

					mapInstance = new google.maps.Map(document.getElementById(this.mapId), {
						center: coordinates,
						zoom: 4,
						mapId: this.mapId,
						mapTypeControl: false,
						fullscreenControl: false,
						streetViewControl: false,
						zoomControl: !this.$store.screen.isMobile
					});

					this.$store.locator.mapInstance = mapInstance;
					this.$store.locator.updateDistances();

					mapInstance.addListener('idle', () => {
                        this.$store.locator.updateDistances();
						this.updateUrlParams();
					});
				} catch (error) {
					console.error('Erreur lors de l\'initialisation de la carte:', error);
					throw error;
				}
			},

			updateUrlParams() {
				if (!mapInstance) return;

				try {
					const center = mapInstance.getCenter();
					const newUrl = new URL(window.location.href);

					const validation = this.$store.locator.validateCoordinates(
						center.lat(),
						center.lng()
					);

					if (validation.isValid) {
						newUrl.searchParams.set('lat', validation.coordinates.lat.toFixed(6));
						newUrl.searchParams.set('lng', validation.coordinates.lng.toFixed(6));
						window.history.replaceState({}, '', newUrl.toString());
					}
				} catch (error) {
					console.error('Erreur lors de la mise à jour des paramètres URL:', error);
				}
			},

            createMarkerElement(isSelected = false) {
                const container = document.createElement('div');
                container.className = `relative group`;

	            const baseClass = isSelected
		            ? 'text-black hover:text-neutral-900'
		            : 'text-brand-500 hover:text-brand-600';

	            const detailPathClass = isSelected
		            ? 'fill-white'
		            : 'fill-black group-hover:fill-white';

	            container.innerHTML = `
                    <svg width="41" height="49" viewBox="0 0 41 49" fill="none" xmlns="http://www.w3.org/2000/svg" class="transition-colors duration-200 ${baseClass}">
                        <path d="M21.5709 48.2273L21.5709 48.2274L21.5759 48.2246L21.6419 48.1875L21.6438 48.1864C21.6843 48.1634 21.7407 48.1311 21.8121 48.0894L21.56 47.6576L21.8121 48.0894C21.9549 48.006 22.1575 47.8852 22.4115 47.7276C22.9191 47.4126 23.6333 46.9495 24.4855 46.3428C26.186 45.132 28.4554 43.3354 30.7311 40.9871C35.2546 36.3193 40 29.2591 40 20.1495C40 9.30109 31.2732 0.5 20.5 0.5C9.72676 0.5 1 9.30109 1 20.1495C1 29.2591 5.74544 36.3193 10.2689 40.9871C12.5446 43.3354 14.814 45.132 16.5145 46.3428C17.3667 46.9495 18.0809 47.4126 18.5885 47.7276C18.8425 47.8852 19.0451 48.006 19.1879 48.0894L19.44 47.6576L19.1879 48.0894C19.2593 48.1311 19.3157 48.1634 19.3562 48.1864L19.358 48.1874L19.4223 48.2236L19.4252 48.2252C20.0904 48.5932 20.9089 48.5892 21.5709 48.2273Z" fill="currentColor" stroke="white" stroke-linejoin="round"/>
                        <path class="${detailPathClass}" fill-rule="evenodd" clip-rule="evenodd" d="M28.7676 24.4986H13.331L13.3631 24.2493C13.6217 22.2282 14.5391 20.5823 16.0902 19.3575C17.6352 18.1364 19.3937 17.5171 21.3176 17.5171C23.2957 17.5171 24.9873 18.1205 26.3448 19.3103C27.7007 20.5 28.5066 22.1623 28.7402 24.2526L28.7676 24.4986ZM21.3177 16.3559C18.779 16.3559 16.5538 17.2136 14.7033 18.9055C12.8579 20.5945 11.9218 22.8317 11.9218 25.5549C11.9218 28.2532 12.8448 30.4591 14.6654 32.1118C16.4887 33.7672 18.6502 34.6064 21.0888 34.6064C23.1885 34.6064 25.0014 34.1216 26.4777 33.1652C27.8869 32.2525 28.9513 30.9261 29.6455 29.2188L28.4592 28.9541C27.1369 31.9591 24.6588 33.4816 21.0888 33.4816C19.0591 33.4816 17.2387 32.7608 15.6782 31.3391C14.1162 29.9147 13.3108 28.0068 13.2844 25.6664L13.2819 25.4418H30.1426V25.007C30.0432 22.4551 29.1634 20.349 27.5265 18.7549C25.8926 17.1631 23.8038 16.3559 21.3177 16.3559Z"/>
                        <path class="${detailPathClass}" fill-rule="evenodd" clip-rule="evenodd" d="M23.7425 10.5L23.7384 10.6097C23.7105 11.4097 23.4413 12.0745 22.9371 12.585C22.403 13.1245 21.724 13.3984 20.9195 13.3984C20.1349 13.3984 19.467 13.1252 18.9334 12.5855C18.4282 12.0754 18.1584 11.4102 18.1305 10.6097L18.1271 10.5H16.9199L16.9226 10.6172C16.9521 11.7614 17.3271 12.6959 18.0383 13.396C18.7816 14.1286 19.7507 14.5 20.9195 14.5C22.0885 14.5 23.0573 14.1286 23.8008 13.396C24.5119 12.6964 24.8875 11.7617 24.917 10.6172L24.9199 10.5H23.7425Z"/>
                    </svg>
                `;

                return container;
            },

			updateMarkersFromStore() {
				if (!markerLib || !mapInstance) return;

				try {
					this.clearMarkers();
					const validStores = this.$store.locator.allStores.filter(store => {
						const validation = this.$store.locator.validateCoordinates(store.lat, store.lng);
						if (!validation.isValid) {
							console.warn(`Marqueur ignoré pour le store ${store.id || 'Unknown'}: ${validation.error}`);
							return false;
						}
						return true;
					});

					this.markers = validStores.map(store => {
						const validation = this.$store.locator.validateCoordinates(store.lat, store.lng);
						const position = validation.coordinates;

						const marker = new markerLib.AdvancedMarkerElement({
							position,
							content: this.createMarkerElement(),
							map: mapInstance
						});

						this.addMarkerEvents(marker, store);
						return marker;
					});

					this.createMarkerCluster(this.markers);
				} catch (error) {
					console.error('Erreur lors de la mise à jour des marqueurs:', error);
				}
			},
			clearMarkers() {
				try {
					if (this.markerCluster) {
						this.markerCluster.setMap(null);
					}
					this.markers.forEach(marker => marker.setMap(null));
					this.markers = [];
				} catch (error) {
					console.error('Erreur lors du nettoyage des marqueurs:', error);
				}
			},
			createMarkerCluster(markersToCluster) {
				if (!mapInstance || !markersToCluster.length) return;

				try {
					this.markerCluster = new markerClusterer.MarkerClusterer({
						markers: markersToCluster,
						map: mapInstance,
						ignoreHidden: true,
						algorithm: new markerClusterer.SuperClusterAlgorithm({
							radius: 150,
							maxZoom: 12
						}),
						renderer: {
							render: ({count, position}) => {
								let size = 56;

								if (count < 10) size = 40;
								else if (count >= 100) size = 72;

								const container = document.createElement('div');
								container.className = `
                                    flex items-center justify-center
                                    rounded-full
                                    text-black text-body-lg font-bold
                                    ring-2 ring-brand-500/32
                                    bg-brand-500
                                    transition-all duration-200
                                    hover:ring-[6px] hover:bg-brand-600 hover:text-white
                                `;

								container.style.width = `${size}px`;
								container.style.height = `${size}px`;

								container.textContent = count;

								return new markerLib.AdvancedMarkerElement({
									position,
									content: container
								});
							}
						}
					});
				} catch (error) {
					console.error('Erreur lors de la création du cluster de marqueurs:', error);
				}
			},
			showStorePopup(store) {
				const content = this.createInfoWindowContent(store);
				const closeBtn = content.querySelector('[data-close]');

				if (this.$store.screen.isMobile) {
					const layer = document.createElement('div');
					layer.className = "fixed inset-0 z-[9999] bg-white p-4 overflow-auto";
					closeBtn?.addEventListener('click', () => {
                        layer.remove();
                        this.closeInfoWindow();
                    });
					layer.appendChild(content);
					document.body.appendChild(layer);
				} else {
					const position = new google.maps.LatLng(store.lat, store.lng);
					this.$store.locator.setMapCenter(store.lat, store.lng);
					closeBtn?.addEventListener('click', () => this.closeInfoWindow());
					this.infoWindow = new this.CustomOverlayWindow(position, content, this.$store.locator.mapInstance);
				}
			},

			addMarkerEvents(marker, store) {
                marker.addListener('gmp-click', () => {
                    if (this.infoWindow) {
                        this.infoWindow.close();
                    }

                    if (this.selectedMarker) {
                        this.selectedMarker.setMap(null);
                    }

                    const selected = new markerLib.AdvancedMarkerElement({
                        position: { lat: parseFloat(store.lat), lng: parseFloat(store.lng) },
                        content: this.createMarkerElement(true),
                        map: mapInstance
                    });

                    this.addMarkerEvents(selected, store);
                    this.selectedMarker = selected;

                    this.showStorePopup(store);
                });
			},
			createInfoWindowContent(store) {
				const div = document.createElement('div');
				div.className = "max-md:fixed max-md:inset-0 w-full h-full bg-white z-[9999]";
				div.innerHTML = `{% render "@info-store" %}`;

				return div;
			},
			closeInfoWindow() {
				this.infoWindow.close();
                this.selectedMarker.setMap(null);
                this.selectedMarker = null;
			}
		};
	}
</script>
{
  "mapId": "DEMO_MAP_ID",
  "loading": false
}

No notes defined.