import { useState, useEffect } from 'react';
import showToast from '../services/toastService';

let hasShownLocationErrorToast = false; // global flag

export const usePositionTracker = () => {
  const [coords, setCoords] = useState({ latitude: 0, longitude: 0 });

  useEffect(() => {
    const locationID = navigator.geolocation.watchPosition(
      ({ coords }) => {
        setCoords(coords);
      },
      (error) => {
        if (!hasShownLocationErrorToast) {
          showToast("Please Allow Location", "warn");
          hasShownLocationErrorToast = true;
        }
      },
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );

    return () => navigator.geolocation.clearWatch(locationID);
  }, []);

  return coords;
};
