'use client';
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { MapPin, DollarSign, X, Navigation } from 'lucide-react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
});
export default function PropertyMap({ properties, onPropertySelect }) {
const [selectedProperty, setSelectedProperty] = useState(null);
const [mapLoaded, setMapLoaded] = useState(false);
const mapRef = useRef(null);
const mapInstanceRef = useRef(null);
const markersRef = useRef([]);
useEffect(() => {
if (!mapRef.current || mapInstanceRef.current) return;
const map = L.map(mapRef.current).setView([34.8021, 38.9968], 7);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 19,
}).addTo(map);
mapInstanceRef.current = map;
setMapLoaded(true);
return () => {
if (mapInstanceRef.current) {
mapInstanceRef.current.remove();
mapInstanceRef.current = null;
}
};
}, []);
useEffect(() => {
if (!mapInstanceRef.current || !properties.length) return;
markersRef.current.forEach(marker => marker.remove());
markersRef.current = [];
const customIcon = L.divIcon({
className: 'custom-marker',
html: `
`,
iconSize: [40, 40],
iconAnchor: [20, 40],
popupAnchor: [0, -40],
});
properties.forEach(property => {
if (property.location?.lat && property.location?.lng) {
const marker = L.marker([property.location.lat, property.location.lng], { icon: customIcon })
.addTo(mapInstanceRef.current)
.on('click', () => {
setSelectedProperty(property);
onPropertySelect?.(property);
});
marker.bindTooltip(property.title, {
permanent: false,
direction: 'top',
offset: [0, -40],
className: 'property-tooltip'
});
markersRef.current.push(marker);
}
});
if (markersRef.current.length > 0) {
const group = L.featureGroup(markersRef.current);
mapInstanceRef.current.fitBounds(group.getBounds(), { padding: [50, 50] });
}
}, [properties, mapLoaded, onPropertySelect]);
return (
{selectedProperty && (
{selectedProperty.title}
{selectedProperty.location?.address || `${selectedProperty.location.city}، ${selectedProperty.location.district}`}
يومي
{selectedProperty.priceDisplay?.daily?.toLocaleString() || selectedProperty.price?.toLocaleString()} ل.س
شهري
{selectedProperty.priceDisplay?.monthly?.toLocaleString() || (selectedProperty.price * 30)?.toLocaleString()} ل.س
)}
);
}