import type { Coordinates, LocationData } from "@/types/location";

const STORAGE_KEY = "doliplay_location";
const NOMINATIM_UA = "Doliplay-Marketplace/1.0";

export function getCurrentPosition(): Promise<GeolocationPosition> {
  return new Promise((resolve, reject) => {
    if (typeof window === "undefined" || !navigator.geolocation) {
      reject(new Error("Geolocation not supported"));
      return;
    }
    navigator.geolocation.getCurrentPosition(resolve, reject, {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 300000,
    });
  });
}

export async function reverseGeocode(coords: Coordinates): Promise<LocationData> {
  const res = await fetch(
    `https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords.lat}&lon=${coords.lng}&accept-language=en`,
    { headers: { "User-Agent": NOMINATIM_UA } }
  );
  if (!res.ok) throw new Error("Reverse geocode failed");
  const data = await res.json();
  const addr = data.address ?? {};
  return {
    coordinates: coords,
    address: data.display_name ?? "",
    city:
      addr.city ?? addr.town ?? addr.village ?? addr.county ?? "",
    state: addr.state ?? "",
    country: addr.country ?? "",
    postalCode: addr.postcode ?? "",
    displayName:
      [addr.suburb ?? addr.neighbourhood, addr.city ?? addr.town ?? addr.village]
        .filter(Boolean)
        .join(", ") || data.display_name || "",
  };
}

export async function geocodeCity(query: string): Promise<Coordinates | null> {
  try {
    const res = await fetch(
      `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=1&accept-language=en`,
      { headers: { "User-Agent": NOMINATIM_UA } }
    );
    if (!res.ok) return null;
    const results = await res.json();
    if (!results.length) return null;
    return { lat: parseFloat(results[0].lat), lng: parseFloat(results[0].lon) };
  } catch {
    return null;
  }
}

export function saveLocation(data: LocationData): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
  } catch {}
}

export function getSavedLocation(): LocationData | null {
  try {
    if (typeof window === "undefined") return null;
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? (JSON.parse(raw) as LocationData) : null;
  } catch {
    return null;
  }
}

export function clearSavedLocation(): void {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch {}
}
