type PropertyMapProps = {
  title: string;
  lat: number;
  lng: number;
};

function buildOpenStreetMapEmbedUrl(lat: number, lng: number) {
  const delta = 0.01;
  const left = lng - delta;
  const bottom = lat - delta;
  const right = lng + delta;
  const top = lat + delta;
  const bbox = `${left},${bottom},${right},${top}`;
  return `https://www.openstreetmap.org/export/embed.html?bbox=${encodeURIComponent(
    bbox,
  )}&layer=mapnik&marker=${encodeURIComponent(`${lat},${lng}`)}`;
}

function buildGoogleMapsEmbedUrl(lat: number, lng: number, apiKey: string) {
  const query = `${lat},${lng}`;
  return `https://www.google.com/maps/embed/v1/place?key=${encodeURIComponent(
    apiKey,
  )}&q=${encodeURIComponent(query)}`;
}

export function PropertyMap({ title, lat, lng }: PropertyMapProps) {
  const googleMapsKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_EMBED_API_KEY;
  const embedUrl = googleMapsKey
    ? buildGoogleMapsEmbedUrl(lat, lng, googleMapsKey)
    : buildOpenStreetMapEmbedUrl(lat, lng);

  const openInMapsUrl = googleMapsKey
    ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(`${lat},${lng}`)}`
    : `https://www.openstreetmap.org/?mlat=${encodeURIComponent(lat)}&mlon=${encodeURIComponent(lng)}#map=16/${lat}/${lng}`;

  return (
    <div className="space-y-3">
      <div className="aspect-[16/10] w-full overflow-hidden rounded-[22px] border border-border bg-white/60">
        <iframe
          title={`${title} map`}
          src={embedUrl}
          className="h-full w-full"
          loading="lazy"
          referrerPolicy="no-referrer-when-downgrade"
          allowFullScreen
        />
      </div>

      <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
        <p className="text-muted">
          {lat.toFixed(5)}, {lng.toFixed(5)}
        </p>
        <a
          href={openInMapsUrl}
          target="_blank"
          rel="noreferrer"
          className="font-medium text-primary underline underline-offset-4 hover:text-primary/80"
        >
          Open in maps
        </a>
      </div>
    </div>
  );
}
