import { useMemo } from 'react';
import { Marker } from '@vis.gl/react-maplibre';
import { useMapStore } from '../../store/mapStore';
import { midpointOf, centroid } from './measureLayers';

/** 완료된 측정 결과의 지우기 버튼을 Marker로 렌더 */
export function MeasureOverlay() {
  const measurements = useMapStore((s) => s.measurements);
  const removeMeasurement = useMapStore((s) => s.removeMeasurement);

  const markers = useMemo(() => {
    return measurements.map((m) => {
      const pos = m.mode === 'distance' ? midpointOf(m.points[0], m.points[1]) : centroid(m.points);
      return { id: m.id, lon: pos[0], lat: pos[1] };
    });
  }, [measurements]);

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

  return (
    <>
      {markers.map((mk) => (
        <Marker key={mk.id} longitude={mk.lon} latitude={mk.lat} anchor="top" offset={[0, 12]}>
          <button
            onClick={(e) => {
              e.stopPropagation();
              removeMeasurement(mk.id);
            }}
            className="px-2 py-0.5 text-label-2 font-semibold text-white bg-[rgba(239,68,68,0.85)] hover:bg-[rgba(239,68,68,1)] rounded shadow-lg border border-[rgba(255,255,255,0.2)] cursor-pointer font-korean"
          >
            지우기
          </button>
        </Marker>
      ))}
    </>
  );
}
