const MAPBOX_TOKEN = process.env.NEXT_PUBLIC_MAPBOX_TOKEN || '';

/**
 * Check if a string looks like GPS coordinates
 */
export const isGPSCoordinates = (str: string): { lat: number; lng: number } | null => {
    if (!str) return null;
    const match = str.match(/^(-?\d+\.?\d*)[,\s]+(-?\d+\.?\d*)$/);
    if (match) {
        const lat = parseFloat(match[1]);
        const lng = parseFloat(match[2]);
        if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
            return { lat, lng };
        }
    }
    return null;
};

/**
 * Reverse geocode GPS coordinates to a place name via Mapbox
 */
export const reverseGeocode = async (lat: number, lng: number): Promise<string | null> => {
    try {
        const res = await fetch(
            `https://api.mapbox.com/geocoding/v5/mapbox.places/${lng},${lat}.json?access_token=${MAPBOX_TOKEN}&types=place,locality,neighborhood,address`
        );
        const data = await res.json();
        if (data.features && data.features.length > 0) {
            const feature = data.features[0];
            let placeName = feature.text;
            const country = feature.context?.find((c: { id: string; text: string }) => c.id.startsWith('country'));
            if (country) {
                placeName = `${feature.text}, ${country.text}`;
            }
            return placeName;
        }
    } catch (error) {
        console.error('Reverse geocode error:', error);
    }
    return null;
};
