import { serviceAreaToSlug } from '@ehandyhire/shared';
import { findNearestServiceArea } from '@/lib/geocode';

/** Rough bounding box for the Philippines archipelago. */
const PH_BOUNDS = {
  minLat: 4.5,
  maxLat: 21.2,
  minLng: 116,
  maxLng: 127,
};

export function isWithinPhilippines(lat: number, lng: number): boolean {
  return (
    lat >= PH_BOUNDS.minLat &&
    lat <= PH_BOUNDS.maxLat &&
    lng >= PH_BOUNDS.minLng &&
    lng <= PH_BOUNDS.maxLng
  );
}

/** Map GPS coordinates to the nearest supported city slug, or null if outside PH. */
export function slugFromCoordinates(lat: number, lng: number): string | null {
  if (!isWithinPhilippines(lat, lng)) return null;
  const area = findNearestServiceArea(lat, lng);
  return serviceAreaToSlug(area);
}

function getCurrentPosition(): Promise<GeolocationCoordinates> {
  return new Promise((resolve, reject) => {
    if (typeof navigator === 'undefined' || !navigator.geolocation) {
      reject(new Error('Geolocation unavailable'));
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (position) => resolve(position.coords),
      reject,
      {
        enableHighAccuracy: false,
        timeout: 10000,
        maximumAge: 300000,
      }
    );
  });
}

/** Request browser location and return the nearest city slug, or null on failure/denial. */
export async function detectRegionSlugFromBrowser(): Promise<string | null> {
  try {
    const coords = await getCurrentPosition();
    return slugFromCoordinates(coords.latitude, coords.longitude);
  } catch {
    return null;
  }
}
