"use client";
import { useState, useEffect, useRef } from "react";
import { Loader2, MapPin } from "lucide-react";
import { geocodeCity } from "@/services/locationService";
import type { Coordinates } from "@/types/location";

interface MapEmbedProps {
  city?: string;
  area?: string;
  lat?: number;
  lng?: number;
  height?: number;
  zoom?: number;
}

export function MapEmbed({
  city,
  area,
  lat: propLat,
  lng: propLng,
  height = 200,
  zoom = 14,
}: MapEmbedProps) {
  const [coords, setCoords] = useState<Coordinates | null>(
    propLat != null && propLng != null ? { lat: propLat, lng: propLng } : null
  );
  const [loading, setLoading] = useState(false);
  const lastQuery = useRef("");

  useEffect(() => {
    if (propLat != null && propLng != null) {
      setCoords({ lat: propLat, lng: propLng });
      return;
    }

    const query = [area, city].filter(Boolean).join(", ");
    if (!query || query === lastQuery.current) return;
    lastQuery.current = query;

    setLoading(true);
    geocodeCity(query).then((c) => {
      if (c) setCoords(c);
      setLoading(false);
    });
  }, [city, area, propLat, propLng]);

  if (loading) {
    return (
      <div
        className="rounded-xl overflow-hidden flex items-center justify-center"
        style={{
          height,
          background: "var(--deep)",
          border: "1px solid var(--border)",
        }}
      >
        <div
          className="flex items-center gap-2 text-sm"
          style={{ color: "var(--text-muted)" }}
        >
          <Loader2 size={16} className="animate-spin" />
          Loading map…
        </div>
      </div>
    );
  }

  if (!coords) return null;

  const delta = zoom <= 13 ? 0.02 : 0.008;
  const bbox = `${coords.lng - delta},${coords.lat - delta},${coords.lng + delta},${coords.lat + delta}`;
  const src = `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${coords.lat},${coords.lng}`;

  return (
    <div className="relative rounded-xl overflow-hidden" style={{ height }}>
      <iframe
        src={src}
        width="100%"
        height={height}
        style={{ border: "none", display: "block" }}
        title="Location map"
        loading="lazy"
      />
      {/* Attribution overlay */}
      <div
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          background: "rgba(255,255,255,0.9)",
          backdropFilter: "blur(4px)",
          padding: "4px 10px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 8,
          pointerEvents: "none",
        }}
      >
        {(area || city) && (
          <span
            style={{
              fontSize: 10,
              fontWeight: 700,
              color: "#1a1a1a",
              display: "flex",
              alignItems: "center",
              gap: 4,
            }}
          >
            <MapPin size={10} color="#fc0000" />
            {[area, city].filter(Boolean).join(", ")}
          </span>
        )}
        <span style={{ fontSize: 9, color: "#888", marginLeft: "auto" }}>
          © OpenStreetMap · Approximate location
        </span>
      </div>
    </div>
  );
}
