// import { MapContainer, TileLayer, Marker, useMap } from "react-leaflet";
// import { useState, useEffect, useRef, useMemo } from "react";
// import { useDispatch } from "react-redux";
// import { useTranslations } from "next-intl";
// import "leaflet/dist/leaflet.css";
// import L from "leaflet";
// import markerIcon from "leaflet/dist/images/marker-icon.png";
// import markerShadow from "leaflet/dist/images/marker-shadow.png";
// import { GeoSearchControl, OpenStreetMapProvider } from "leaflet-geosearch";
// import "leaflet-geosearch/dist/geosearch.css";
// import { fetchLatLngSuccess } from "@/store/map/actions";
// interface Props{
//   lat?: any;
//   lng?: any;
//   setAddress?: any;
// }

// const Map: React.FC<Props> = ({lat,lng,setAddress}) => {
//   const center = { lat: lat?lat: 23.8859, lng: lng?lng:45.0792 };
//   const [position, setPosition] = useState(center);
//   const markerRef = useRef<L.Marker>(null);
//   const mapRef = useRef<L.Map | null>(null);
//   const dispatch = useDispatch()
// const t = useTranslations()
//   // Custom Marker Icon
//   const customIcon = new L.Icon({
//     // iconUrl: (markerIcon as any).default || markerIcon,
//     // shadowUrl: (markerShadow as any).default || markerShadow,
//     iconUrl: '/images/marker.svg',
//    // shadowUrl: '/images/marker.svg',
//     iconSize: [25, 41],
//     iconAnchor: [12, 41],
//     popupAnchor: [1, -34],
//     shadowSize: [41, 41],
//   });

//   // Fetch Address for Selected Coordinates
//   const fetchAddress = async (lat: number, lng: number) => {
//     const response = await fetch(
//       `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`
//     );
//     const data = await response.json();
//     const address = data?.display_name || "Unknown location";
//    // console.log("Address:", address);
//     //console.log("Address'LatLng:", lat,lng);
//     setAddress(address);
//     dispatch(fetchLatLngSuccess({lat:`${lat}`,lng:`${lng}`}));
    
//   };

//   // Drag Event Handler for Marker
//   const eventHandlers = useMemo(
//     () => ({
//       dragend() {
//         const marker = markerRef.current;
//         if (marker) {
//           const newPos = marker.getLatLng();
//           setPosition(newPos);
//           fetchAddress(newPos.lat, newPos.lng)
          
//         }
//       },
//     }),
//     []
//   );

//   // Search Control Component
//   // const SearchControl: React.FC = () => {
//   //   const map = useMap();

//   //   useEffect(() => {
//   //     if (!map) return;
//   //     mapRef.current = map;

//   //     const provider = new OpenStreetMapProvider();
//   //     const searchControl = new (GeoSearchControl as any)({
//   //       provider,
//   //       style: "bar",
//   //       showMarker: false,
//   //       showPopup: false,
//   //       keepResult: true,
//   //     });

//   //     map.addControl(searchControl);

//   //     map.on("geosearch/showlocation", (result: any) => {
//   //       const { x, y } = result.location;
//   //       setPosition({ lat: y, lng: x });

//   //       // Move the marker to the searched location
//   //       if (markerRef.current) {
//   //         markerRef.current.setLatLng([y, x]);
//   //       }

//   //       fetchAddress(y, x);
//   //     });

//   //     return () => {
//   //       map.removeControl(searchControl);
//   //     };
//   //   }, [map]);

//   //   return null;
//   // };
//   const SearchControl: React.FC = () => {
//     const map = useMap();
//     const isEventListenerAttached = useRef(false); // Track event listener
    
//     useEffect(() => {
//       if (!map || isEventListenerAttached.current) return; // Prevent duplicate listeners
  
//       mapRef.current = map;
//       isEventListenerAttached.current = true; // Mark as attached
  
//       const provider = new OpenStreetMapProvider();
//       const searchControl = new (GeoSearchControl as any)({
//         provider,
//         style: "bar",
//         showMarker: false,
//         showPopup: false,
//         searchLabel: t("enter-address"),
//         keepResult: true,
//       });
  
//       map.addControl(searchControl);
  
//       // Handle search location event
//       const handleSearchLocation = (result: any) => {
//         const { x, y } = result.location;
//         setPosition({ lat: y, lng: x });
  
//         if (markerRef.current) {
//           markerRef.current.setLatLng([y, x]);
//         }
  
//         fetchAddress(y, x);
//       };
  
//       map.on("geosearch/showlocation", handleSearchLocation);
  
//       return () => {
//         map.removeControl(searchControl);
//         map.off("geosearch/showlocation", handleSearchLocation);
//         isEventListenerAttached.current = false; // Reset when component unmounts
//       };
//     }, [map]);
  
//     return null;
//   };
  

//   return (
//     <MapContainer
//       center={center}
//       zoom={13}
//       scrollWheelZoom={false}
//       style={{ width: "100%", height: "400px" }}
//       ref={mapRef}
//     >
//       <TileLayer
//         attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
//         url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
//       />
//       <SearchControl />
//       <Marker
//         draggable
//         eventHandlers={eventHandlers}
//         position={position}
//         ref={markerRef}
//         icon={customIcon}
//       />
//     </MapContainer>
//   );
// };

// export default Map;






//// image not permmission


// import { MapContainer, TileLayer, Marker, Popup, useMapEvents,useMap } from "react-leaflet";
// import { useState, useRef, useEffect } from "react";
// import { useDispatch } from "react-redux";
// import { useTranslations } from "next-intl";
// import "leaflet/dist/leaflet.css";
// import L from "leaflet";
// import { GeoSearchControl, OpenStreetMapProvider } from "leaflet-geosearch";
// import "leaflet-geosearch/dist/geosearch.css";
// import { fetchLatLngSuccess } from "@/store/map/actions";

// interface Props {
//   lat?: number;
//   lng?: number;
//   setAddress: (address: string) => void;
// }
// const MapClickHandler = ({ setPosition, fetchAddress }: any) => {
//   const map = useMap();

//   useMapEvents({
//     click: (e) => {
//       const newPos = e.latlng;
//       setPosition(newPos);
//       fetchAddress(newPos.lat, newPos.lng);
//     },
//   });

//   return null;
// };
// const Map: React.FC<Props> = ({ lat, lng, setAddress }) => {
//   const center = { lat: lat ?lat: 23.8859, lng: lng ?lng: 45.0792 };
//   const [position, setPosition] = useState<L.LatLngExpression>(center);
//   const [showLocationPopup, setShowLocationPopup] = useState(true);
//   const markerRef = useRef<L.Marker>(null);
//   const mapRef = useRef<L.Map>(null);
//   const dispatch = useDispatch();
//   const t = useTranslations();

//   // Custom Marker Icon with proper TypeScript typing
//   const customIcon = new L.Icon({
//     iconUrl: '/images/marker.svg',
//     iconSize: [32, 32],
//     iconAnchor: [16, 32],
//     popupAnchor: [0, -32],
//     className: 'custom-marker-icon'
//   });

//   // Handle map clicks with proper typing
//   // const MapClickHandler = () => {
//   //   const map = useMapEvents({
//   //     click: (e: L.LeafletMouseEvent) => {
//   //       const newPos: L.LatLngExpression = [e.latlng.lat, e.latlng.lng];
//   //       setPosition(newPos);
//   //       if (markerRef.current) {
//   //         markerRef.current.setLatLng(newPos);
//   //       }
//   //       fetchAddress(e.latlng.lat, e.latlng.lng);
//   //     },
//   //   });
//   //   return null;
//   // };

//   // Fetch address with proper typing
//   const fetchAddress = async (lat: number, lng: number): Promise<void> => {
//     try {
//       const response = await fetch(
//         `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}&accept-language=ar`
//       );
//       const data = await response.json();
//       const address = data?.display_name || t("unknown-location");
//       setAddress(address);
//       dispatch(fetchLatLngSuccess({ lat: `${lat}`, lng: `${lng}` }));
//     } catch (error) {
//       console.error("Error fetching address:", error);
//       setAddress(t("failed-to-get-address"));
//     }
//   };

//   // Search control with proper typing
//   const SearchControl = () => {
//     const map = useMap();
//     const isEventListenerAttached = useRef(false);

//     useEffect(() => {
//       if (!map || isEventListenerAttached.current) return;
      
//       mapRef.current = map;
//       isEventListenerAttached.current = true;

//       const provider = new OpenStreetMapProvider({
//         params: {
//           "accept-language": "ar",
//           countrycodes: "sa",
//           addressdetails: 1,
//         },
//       });

//       const searchControl = new (GeoSearchControl as any)({
//         provider,
//         style: "bar",
//         showMarker: false,
//         showPopup: false,
//         searchLabel: t("enter-address"),
//         keepResult: true,
//         autoComplete: true,
//         autoCompleteDelay: 250,
//       });

//       map.addControl(searchControl);

//       const handleSearchResult = (result: any) => {
//         const newPos: L.LatLngExpression = [result.location.y, result.location.x];
//         setPosition(newPos);
//         if (markerRef.current) {
//           markerRef.current.setLatLng(newPos);
//         }
//         if (mapRef.current) {
//           mapRef.current.flyTo(newPos, 15);
//         }
//         fetchAddress(result.location.y, result.location.x);
//       };

//       map.on("geosearch/showlocation", handleSearchResult);

//       return () => {
//         map.removeControl(searchControl);
//         map.off("geosearch/showlocation", handleSearchResult);
//         isEventListenerAttached.current = false;
//       };
//     }, [map, t]);

//     return null;
//   };

//   // Get user location with proper typing
//   const getUserLocation = (): void => {
//     if (navigator.geolocation) {
//       navigator.geolocation.getCurrentPosition(
//         (position: GeolocationPosition) => {
//           const newPos: L.LatLngExpression = [
//             position.coords.latitude, 
//             position.coords.longitude
//           ];
//           setPosition(newPos);
//           setShowLocationPopup(false);
//           if (mapRef.current) {
//             mapRef.current.flyTo(newPos, 15);
//           }
//           if (markerRef.current) {
//             markerRef.current.setLatLng(newPos);
//           }
//           fetchAddress(position.coords.latitude, position.coords.longitude);
//         },
//         (error: GeolocationPositionError) => {
//           console.error("Error getting location:", error);
//           setShowLocationPopup(false);
//         },
//         { enableHighAccuracy: true, timeout: 10000 }
//       );
//     } else {
//       console.error("Geolocation is not supported by this browser.");
//       setShowLocationPopup(false);
//     }
//   };

//   return (
    
//       <MapContainer
//         center={position}
//         zoom={13}
//         ref={mapRef}
//         style={{ height: '400px', width: '100%' }}
        
//       >
//         <TileLayer
//           url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
//           attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
//         />
        
//         <SearchControl />
//         {/* <MapClickHandler /> */}
//             <MapClickHandler setPosition={setPosition} fetchAddress={fetchAddress} />
      
//         <Marker
//           position={position}
//           icon={customIcon}
//           ref={markerRef}
//           draggable={true}
//           eventHandlers={{
//             dragend: () => {
//               const marker = markerRef.current;
//               if (marker) {
//                 const newPos = marker.getLatLng();
//                 setPosition(newPos);
//                 fetchAddress(newPos.lat, newPos.lng);
//               }
//             },
//           }}
//         >
//                {showLocationPopup && (
//         <Popup
//           position={position}
//           autoClose={false}
//           closeOnClick={false}
//           closeButton={false}
//           className="location-permission-popup"
//         >
//           <div className="text-center">
//             <p>{t("allow-location-access")}</p>
//             <div className="flex gap-2 mt-2">
//               <button
//                 className="bg-primary text-white px-4 py-1 rounded flex-1"
//                 onClick={() => {
//                   getUserLocation();
//                   setShowLocationPopup(false);
//                 }}
//               >
//                 {t("allow")}
//               </button>
//               <button
//                 className="bg-gray-200 px-4 py-1 rounded flex-1"
//                 onClick={() => setShowLocationPopup(false)}
//               >
//                 {t("cancel")}
//               </button>
//             </div>
//           </div>
//         </Popup>
//       )}
//         </Marker>
//       </MapContainer>
  
//   );
// };

// export default Map;












/***********permission********** */
//  import { MapContainer, TileLayer, Marker, useMap, Popup, useMapEvents } from "react-leaflet";
// import { useState, useEffect, useRef, useMemo } from "react";
// import { useDispatch } from "react-redux";
// import { useTranslations } from "next-intl";
// import "leaflet/dist/leaflet.css";
// import L from "leaflet";
// import { GeoSearchControl, OpenStreetMapProvider } from "leaflet-geosearch";
// import "leaflet-geosearch/dist/geosearch.css";
// import { fetchLatLngSuccess } from "@/store/map/actions";

// interface Props {
//   lat?: any;
//   lng?: any;
//   setAddress?: any;
// }
// // Fix for default marker icons
// delete (L.Icon.Default.prototype as any)._getIconUrl;
// // Custom component to handle map click events
// const MapClickHandler = ({ setPosition, fetchAddress }: any) => {
//   const map = useMap();

//   useMapEvents({
//     click: (e) => {
//       const newPos = e.latlng;
//       setPosition(newPos);
//       fetchAddress(newPos.lat, newPos.lng);
//     },
//   });

//   return null;
// };

// const Map: React.FC<Props> = ({ lat, lng, setAddress }) => {
//   const center = { lat: lat ? lat : 23.8859, lng: lng ? lng : 45.0792 };
//   const [position, setPosition] = useState(center);
//   const [showLocationPopup, setShowLocationPopup] = useState(true);
//   const markerRef = useRef<L.Marker>(null);
//   const mapRef = useRef<L.Map | null>(null);
//   const dispatch = useDispatch();
//   const t = useTranslations();

//   // Custom Marker Icon
//   // const customIcon = new L.Icon({
//   //   // iconUrl: '/images/marker.svg',
//   //   // iconSize: [25, 41],
//   //   // iconAnchor: [12, 41],
//   //   // popupAnchor: [1, -34],
//   //   // shadowSize: [41, 41],
//   //    iconUrl: '/images/marker.svg',
//   //   iconSize: [32, 32],      // Adjust based on your SVG size
//   //   iconAnchor: [16, 32],    // Point of the icon that will correspond to marker's location
//   //   popupAnchor: [0, -32],   // Point from which the popup should open
//   //   className: 'leaflet-marker-icon' // Important for proper cleanup
//   // });
//   // Custom DivIcon with HTML content - prevents broken images
//   const customIcon = new L.DivIcon({
//     html: `
//       <div style="
//         width: 32px;
//         height: 32px;
//         background-image: url('/images/marker.svg');
//         background-size: contain;
//         background-repeat: no-repeat;
//         transform: translate(-50%, -100%);
//       "></div>
//     `,
//     className: 'custom-div-icon',
//     iconSize: [32, 32],
//     iconAnchor: [16, 32],
//     popupAnchor: [0, -32]
//   });

//   // Fetch Address for Selected Coordinates
//   const fetchAddress = async (lat: number, lng: number) => {
//     try {
//       const response = await fetch(
//         `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`
//       );
//       const data = await response.json();
//       const address = data?.display_name || t("unknown-location");
//       setAddress(address);
//       dispatch(fetchLatLngSuccess({ lat: `${lat}`, lng: `${lng}` }));
//       console.log("Address:", lat,lng);
//     } catch (error) {
//       console.error("Error fetching address:", error);
//       setAddress(t("failed-to-get-address"));
//     }
//   };

//   // Get user's current location
//   const getUserLocation = () => {
//     if (navigator.geolocation) {
//       navigator.geolocation.getCurrentPosition(
//         (position) => {
//           const { latitude, longitude } = position.coords;
//           const newPos = { lat: latitude, lng: longitude };
//           setPosition(newPos);
//           setShowLocationPopup(false);
//           if (mapRef.current) {
//             mapRef.current.flyTo(newPos, 15);
//           }
//           if (markerRef.current) {
//             markerRef.current.setLatLng(newPos);
//           }
//           fetchAddress(latitude, longitude);
//         },
//         (error) => {
//           console.error("Error getting location:", error);
//           setShowLocationPopup(false);
//         },
//         { enableHighAccuracy: true, timeout: 10000 }
//       );
//     } else {
//       console.error("Geolocation is not supported by this browser.");
//       setShowLocationPopup(false);
//     }
//   };

//   // Improved search functionality
//   const SearchControl: React.FC = () => {
//     const map = useMap();
//     const isEventListenerAttached = useRef(false);

//     useEffect(() => {
//       if (!map || isEventListenerAttached.current) return;
//       mapRef.current = map;
//       isEventListenerAttached.current = true;

//       const provider = new OpenStreetMapProvider({
//         params: {
//           "accept-language": "ar", // Force Arabic language results
//           countrycodes: "sa", // Prioritize Saudi Arabia results
//           addressdetails: 1,
//         },
//       });

//       const searchControl = new (GeoSearchControl as any)({
//         provider,
//         style: "bar",
//         showMarker: true,
//         showPopup: false,
//         searchLabel: t("enter-address"),
//         keepResult: true,
//         autoClose: false,
//         retainZoomLevel: false,
//         animateZoom: true,
//       });

//       map.addControl(searchControl);

//       const handleSearchLocation = (result: any) => {
//         const { x, y } = result.location;
//         const newPos = { lat: y, lng: x };
//         setPosition(newPos);
        
//         if (markerRef.current) {
//           markerRef.current.setLatLng(newPos);
//         }

//         if (mapRef.current) {
//           mapRef.current.flyTo(newPos, 15);
//         }

//         fetchAddress(y, x);
//       };

//       map.on("geosearch/showlocation", handleSearchLocation);

//       return () => {
//         map.removeControl(searchControl);
//         map.off("geosearch/showlocation", handleSearchLocation);
//         isEventListenerAttached.current = false;
//       };
//     }, [map]);

//     return null;
//   };

//   return (
//     <MapContainer
//       center={center}
//       zoom={13}
//       scrollWheelZoom={true}
//       style={{ width: "100%", height: "400px" }}
//       ref={mapRef}
//     >
//       <TileLayer
//         attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
//         url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
//       />
//       <SearchControl />
//       <Marker
//         draggable
//         position={position}
//         ref={markerRef}
//         icon={customIcon}
//         eventHandlers={{
//           dragend: () => {
//             const marker = markerRef.current;
//             if (marker) {
//               const newPos = marker.getLatLng();
//               setPosition(newPos);
//               fetchAddress(newPos.lat, newPos.lng);
//             }
//           },
//         }}
//       />
      
//       <MapClickHandler setPosition={setPosition} fetchAddress={fetchAddress} />
      
//       {showLocationPopup && (
//         <Popup
//           position={position}
//           autoClose={false}
//           closeOnClick={false}
//           closeButton={false}
//           className="location-permission-popup"
//         >
//           <div className="text-center">
//             <p>{t("allow-location-access")}</p>
//             <div className="flex gap-2 mt-2">
//               <button
//                 className="bg-primary text-white px-4 py-1 rounded flex-1"
//                 onClick={() => {
//                   getUserLocation();
//                   setShowLocationPopup(false);
//                 }}
//               >
//                 {t("allow")}
//               </button>
//               <button
//                 className="bg-gray-200 px-4 py-1 rounded flex-1"
//                 onClick={() => setShowLocationPopup(false)}
//               >
//                 {t("cancel")}
//               </button>
//             </div>
//           </div>
//         </Popup>
//       )}
//     </MapContainer>
//   );
// };

// export default Map;





















import { MapContainer, TileLayer, Marker, Popup, useMapEvents, useMap } from "react-leaflet";
import { useState, useRef, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useTranslations } from "next-intl";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import { GeoSearchControl, OpenStreetMapProvider } from "leaflet-geosearch";
import "leaflet-geosearch/dist/geosearch.css";
import { fetchLatLngSuccess } from "@/store/map/actions";

// Fix for default marker icons
delete (L.Icon.Default.prototype as any)._getIconUrl;

interface Props {
  lat?: number;
  lng?: number;
  setAddress: (address: string) => void;
}

const Map: React.FC<Props> = ({ lat, lng, setAddress }) => {
  const center = { lat: lat || 24.7136, lng: lng || 46.6753 };
  const [position, setPosition] = useState<L.LatLngExpression>(center);
  const [showLocationPopup, setShowLocationPopup] = useState(true);
  const markerRef = useRef<L.Marker>(null);
  const mapRef = useRef<L.Map>(null);
  const popupRef = useRef<any>(null);
  const dispatch = useDispatch();
  const t = useTranslations();

  // Custom DivIcon with HTML content - prevents broken images
  const customIcon = new L.DivIcon({
    html: `
      <div style="
        width: 32px;
        height: 32px;
        background-image: url('/images/marker.svg');
        background-size: contain;
        background-repeat: no-repeat;
        transform: translate(-50%, -100%);
      "></div>
    `,
    className: 'custom-div-icon',
    iconSize: [32, 32],
    iconAnchor: [16, 32],
    popupAnchor: [0, -32]
  });

  // Handle map clicks
  const MapClickHandler = () => {
    useMapEvents({
      click: (e: L.LeafletMouseEvent) => {
        const newPos: L.LatLngExpression = [e.latlng.lat, e.latlng.lng];
        setPosition(newPos);
        if (markerRef.current) {
          markerRef.current.setLatLng(newPos);
        }
        fetchAddress(e.latlng.lat, e.latlng.lng);
      },
    });
    return null;
  };

  // Fetch address from coordinates
  const fetchAddress = async (lat: number, lng: number): Promise<void> => {
    try {
      const response = await fetch(
        `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}&accept-language=ar`
      );
      const data = await response.json();
      const address = data?.display_name || t("unknown-location");
      setAddress(address);
      dispatch(fetchLatLngSuccess({ lat: `${lat}`, lng: `${lng}` }));
      console.log("Address:",lat, lng);
    } catch (error) {
      console.error("Error fetching address:", error);
      setAddress(t("failed-to-get-address"));
    }
  };

  // Search control
  const SearchControl = () => {
    const map = useMap();
    const isEventListenerAttached = useRef(false);

    useEffect(() => {
      if (!map || isEventListenerAttached.current) return;
      
      mapRef.current = map;
      isEventListenerAttached.current = true;

      const provider = new OpenStreetMapProvider({
        params: {
          "accept-language": "ar",
          countrycodes: "sa",
          addressdetails: 1,
        },
      });

      const searchControl = new (GeoSearchControl as any)({
        provider,
        style: "bar",
        showMarker: false,
        showPopup: false,
        searchLabel: t("enter-address"),
        keepResult: true,
        autoComplete: true,
        autoCompleteDelay: 250,
      });

      map.addControl(searchControl);

      const handleSearchResult = (result: any) => {
        const newPos: L.LatLngExpression = [result.location.y, result.location.x];
        setPosition(newPos);
        if (markerRef.current) {
          markerRef.current.setLatLng(newPos);
        }
        if (mapRef.current) {
          mapRef.current.flyTo(newPos, 15);
        }
        fetchAddress(result.location.y, result.location.x);
      };

      map.on("geosearch/showlocation", handleSearchResult);

      return () => {
        map.removeControl(searchControl);
        map.off("geosearch/showlocation", handleSearchResult);
        isEventListenerAttached.current = false;
      };
    }, [map, t]);

    return null;
  };

  // Get user location
  const getUserLocation = (): void => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position: GeolocationPosition) => {
          const newPos: L.LatLngExpression = [
            position.coords.latitude, 
            position.coords.longitude
          ];
          setPosition(newPos);
          setShowLocationPopup(false);
          if (mapRef.current) {
            mapRef.current.flyTo(newPos, 15);
          }
          if (markerRef.current) {
            markerRef.current.setLatLng(newPos);
          }
          fetchAddress(position.coords.latitude, position.coords.longitude);
        },
        (error: GeolocationPositionError) => {
          console.error("Error getting location:", error);
          setShowLocationPopup(false);
        },
        { enableHighAccuracy: true, timeout: 10000 }
      );
    } else {
      console.error("Geolocation is not supported by this browser.");
      setShowLocationPopup(false);
    }
  };

  // Open popup immediately when marker is ready
  // useEffect(() => {
  //   if (markerRef.current && showLocationPopup) {
  //     markerRef.current.openPopup();
  //   }
  // }, [showLocationPopup]);

  const handleClosePopup = () => {
    setShowLocationPopup(false);
    // Prevent marker movement by not updating the position state
  };

  return (
    <div style={{ position: 'relative', width: '100%', height: '400px' }}>
      <MapContainer
        center={position}
        zoom={13}
        ref={mapRef}
        style={{ height: '100%', width: '100%' }}
      >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        />
        
        <SearchControl />
        <MapClickHandler />
        
        <Marker
          position={position}
          icon={customIcon}
          ref={markerRef}
          draggable={true}
          eventHandlers={{
            add: () => {
              if (showLocationPopup && markerRef.current) {
                markerRef.current.openPopup();
              }
            },
            dragend: () => {
              const marker = markerRef.current;
              if (marker) {
                const newPos = marker.getLatLng();
                setPosition(newPos);
                fetchAddress(newPos.lat, newPos.lng);
              }
            },
          }}
        >
          {showLocationPopup && (
            <Popup
              position={position}
              autoClose={false}
              closeOnClick={false}
              closeButton={false}
              className="location-permission-popup"
              //onClose={() => handleClosePopup()}
            >
              <div style={{ textAlign: 'center' }}>
                <p>{t("allow-location-access")}</p>
                <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      getUserLocation();
                    }}
                    style={{
                      background: '#4CAF50',
                      color: 'white',
                      border: 'none',
                      padding: '5px 10px',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      flex: 1
                    }}
                  >
                    {t("allow")}
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleClosePopup();
                    }}
                    style={{
                      background: '#f44336',
                      color: 'white',
                      border: 'none',
                      padding: '5px 10px',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      flex: 1
                    }}
                  >
                    {t("cancel")}
                  </button>
                </div>
              </div>
            </Popup>
          )}
        </Marker>
      </MapContainer>
    </div>
  );
};

export default Map;