import { enqueueSnackbar } from "notistack";
const GOOGLE_MAPS_API_KEY = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;

export function decodePolyline(encoded: string): google.maps.LatLngLiteral[] {
  if (typeof window.google === "undefined" || !window.google.maps || !window.google.maps.geometry) {
    enqueueSnackbar("Google Maps JavaScript API geometry library not loaded. Cannot decode polyline.", { variant: 'warning' })
    return [];
  }
  const decodedPath = window.google.maps.geometry.encoding.decodePath(encoded);
  return decodedPath.map((latLng: any) => ({
    lat: latLng.lat(),
    lng: latLng.lng(),
  }));
}

export async function fetchAddressFromLatLng(lat: number, lng: number): Promise<string> {
  const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${GOOGLE_MAPS_API_KEY}`;
  try {
    const res = await fetch(url);
    const data = await res.json();
    if (data.status === "OK" && data.results.length > 0) {
      return data.results[0].formatted_address;
    }
    return "";
  } catch {
    return "";
  } 
}