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

// Fix default marker icon broken by webpack/vite asset bundling
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',
});

function PharmacyMap({ pharmacies }) {
  const located = pharmacies.filter(p => p.latitude != null && p.longitude != null);

  if (located.length === 0) return null;

  const center = [
    located.reduce((s, p) => s + p.latitude, 0) / located.length,
    located.reduce((s, p) => s + p.longitude, 0) / located.length,
  ];

  return (
    <div className="pharmacy-map-wrapper" style={{ height: '350px', width: '100%', marginTop: '1rem', borderRadius: '8px', overflow: 'hidden' }}>
      <MapContainer center={center} zoom={13} style={{ height: '100%', width: '100%' }} scrollWheelZoom={false}>
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        {located.map(pharmacy => (
          <Marker key={pharmacy.id} position={[pharmacy.latitude, pharmacy.longitude]}>
            <Popup>
              <strong>{pharmacy.name}</strong><br />
              {pharmacy.address}
              {pharmacy.phone && <><br />{pharmacy.phone}</>}
            </Popup>
          </Marker>
        ))}
      </MapContainer>
    </div>
  );
}

export default PharmacyMap;
