import { useEffect } from 'react';
import { useMap } from 'react-leaflet';
import L from 'leaflet';

/**
 * Adds metric scale bar (bottom-left) and a compass rose (top-right, below zoom buttons).
 */
export default function MapExtras() {
  const map = useMap();

  useEffect(() => {
    // Scale bar
    const scale = L.control
      .scale({
        position: 'bottomleft',
        metric: true,
        imperial: false,
        maxWidth: 200,
      })
      .addTo(map);

    // Compass rose
    const CompassControl = L.Control.extend({
      options: { position: 'topright' as L.ControlPosition },
      onAdd() {
        const div = L.DomUtil.create('div', 'compass-rose');
        div.innerHTML = `
          <svg width="40" height="40" viewBox="0 0 40 40" style="display:block;">
            <circle cx="20" cy="20" r="18" fill="rgba(255,255,255,0.9)" stroke="#555" stroke-width="1.5"/>
            <path d="M 20 5 L 23 16 L 20 20 L 17 16 Z" fill="#dc2626"/>
            <path d="M 20 35 L 23 24 L 20 20 L 17 24 Z" fill="#ccc" stroke="#999" stroke-width="0.5"/>
            <text x="20" y="14" text-anchor="middle" font-size="8" font-weight="bold" fill="#333">N</text>
          </svg>`;
        div.style.cssText =
          'border-radius: 50%; box-shadow: 0 2px 5px rgba(0,0,0,0.3); margin-top: 4px; pointer-events: none;';
        return div;
      },
    });

    const compass = new CompassControl();
    compass.addTo(map);

    return () => {
      map.removeControl(scale);
      map.removeControl(compass);
    };
  }, [map]);

  return null;
}
