import React, { useEffect } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

// Añadimos onMarkerClick a las props
const MapComponent = ({ properties, onMarkerClick }: any) => {
  useEffect(() => {
    // Fix para iconos de Leaflet
    // @ts-ignore
    delete L.Icon.Default.prototype._getIconUrl;
    L.Icon.Default.mergeOptions({
      iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
      iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
      shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
    });
  }, []);

  const customIcon = new L.Icon({
    iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-orange.png',
    shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowSize: [41, 41]
  });

  return (
    <div className="tw-w-full tw-h-full" style={{ minHeight: '100%', height: '100%' }}>
      <MapContainer 
        center={[22.33, -97.88]} // Ajustado ligeramente para centrar mejor la zona
        zoom={11} 
        style={{ height: '100%', width: '100%' }} 
        scrollWheelZoom={false}
      >
        <TileLayer url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png" />
        
        {properties.map((prop: any) => (
          <Marker 
            key={prop.id} 
            position={prop.coordinates} 
            icon={customIcon}
            // --- NUEVO: Detectar clic en el marcador ---
            eventHandlers={{
              click: () => {
                if (onMarkerClick) onMarkerClick(prop.id);
              },
            }}
          >
            <Popup>
               <div className="font-barlow">
                 <strong className="tw-text-main-dark">{prop.name}</strong><br/>
                 <span className="tw-text-gray-500 tw-text-xs">📍 {prop.location}</span>
               </div>
            </Popup>
          </Marker>
        ))}
      </MapContainer>
    </div>
  );
};

export default MapComponent;