import { useCallback } from 'react';
import { useMapStore } from '../store/mapStore';
import { haversineDistance } from '../utils/geo';

const CLOSE_THRESHOLD_M = 200;

export function useMeasureTool() {
  const measureMode = useMapStore((s) => s.measureMode);
  const measureInProgress = useMapStore((s) => s.measureInProgress);
  const addMeasurePoint = useMapStore((s) => s.addMeasurePoint);
  const commitAreaMeasurement = useMapStore((s) => s.commitAreaMeasurement);

  const handleMeasureClick = useCallback(
    (lon: number, lat: number) => {
      if (!measureMode) return;

      const pt = { lat, lon };

      // 면적 모드: 첫 점 근처 클릭 시 다각형 닫기
      if (measureMode === 'area' && measureInProgress.length >= 3) {
        const first = measureInProgress[0];
        const dist = haversineDistance(first, pt);
        if (dist < CLOSE_THRESHOLD_M) {
          commitAreaMeasurement();
          return;
        }
      }

      addMeasurePoint(pt);
    },
    [measureMode, measureInProgress, addMeasurePoint, commitAreaMeasurement],
  );

  return { handleMeasureClick, measureMode };
}
