/* eslint-disable no-unused-vars */
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

// distance function (same)
function distance(lat1, lng1, lat2, lng2) {
  const R = 6371;
  const dLat = (lat2 - lat1) * (Math.PI / 180);
  const dLng = (lng2 - lng1) * (Math.PI / 180);

  const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) * Math.sin(dLng / 2) ** 2;

  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

const center = [11.015181, 76.953682];

const riders = [
  { id: 1, lat: 11.04362, lng: 76.924667 },
  { id: 2, lat: 11.00988, lng: 76.949966 },
  { id: 3, lat: 11.020983, lng: 76.966331 }
];

export default function RidersPinPointOSM() {
  const sortedRiders = riders
    .map((r) => ({
      ...r,
      distance: distance(center[0], center[1], r.lat, r.lng)
    }))
    .sort((a, b) => a.distance - b.distance);

  // purple center marker
  const centerIcon = L.icon({
    iconUrl: 'https://maps.google.com/mapfiles/ms/icons/purple-dot.png',
    iconSize: [32, 32]
  });

  // basic numbered marker icon
  const createMarkerIcon = (number) =>
    L.divIcon({
      className: 'custom-marker',
      html: `
        <div style="
          background:#007bff;
          color:white;
          width:28px;
          height:28px;
          border-radius:50%;
          display:flex;
          align-items:center;
          justify-content:center;
          font-weight:bold;
          border:2px solid white;
        ">
          ${number}
        </div>
      `,
      iconSize: [30, 30],
      iconAnchor: [15, 15]
    });

  return (
    <MapContainer center={center} zoom={14} style={{ height: '300px', width: '100%' }}>
      {/* OSM tiles */}
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />

      {/* Purple center marker */}
      <Marker position={center} icon={centerIcon} />

      {/* Sorted rider markers */}
      {sortedRiders.map((r, index) => (
        <Marker key={r.id} position={[r.lat, r.lng]} icon={createMarkerIcon(index + 1)}>
          <Popup>Rider {index + 1}</Popup>
        </Marker>
      ))}
    </MapContainer>
  );
}
