// HLP Raf — Selector de ubicación con pin arrastrable (Google Maps)
// Muestra un mapa con un marcador que el cliente puede arrastrar / tocar para
// marcar el punto exacto. Si no hay key de Maps o falla la carga, avisa arriba.

function PinPicker({ coords, accent, onChange, height = 240 }) {
  const boxRef = React.useRef(null);
  const markerRef = React.useRef(null);
  const [status, setStatus] = React.useState("loading"); // loading | ok | error
  const onChangeRef = React.useRef(onChange);
  onChangeRef.current = onChange;

  React.useEffect(() => {
    let cancelled = false;
    if (!window.hlprafMaps || !hlprafMaps.hasMapsKey()) { setStatus("error"); return; }
    hlprafMaps.loadGoogleMaps().then((g) => {
      if (cancelled || !boxRef.current) return;
      const center = { lat: coords.lat, lng: coords.lng };
      const map = new g.maps.Map(boxRef.current, {
        center, zoom: 16, disableDefaultUI: true, zoomControl: true,
        gestureHandling: "greedy", clickableIcons: false,
      });
      const marker = new g.maps.Marker({
        position: center, map, draggable: true, animation: g.maps.Animation.DROP,
      });
      const emit = (latLng) => onChangeRef.current({ lat: latLng.lat(), lng: latLng.lng() });
      marker.addListener("dragend", () => emit(marker.getPosition()));
      map.addListener("click", (e) => { marker.setPosition(e.latLng); emit(e.latLng); });
      markerRef.current = marker;
      setStatus("ok");
    }).catch(() => { if (!cancelled) setStatus("error"); });
    return () => { cancelled = true; };
  }, []);

  if (status === "error") {
    return (
      <div style={{ background: "#fff7ed", border: "1px solid #f0e0c8", borderRadius: 12, padding: "12px 14px", fontSize: 12.5, color: "#8a7a66", fontFamily: "'DM Sans', sans-serif" }}>
        No se pudo cargar el mapa acá. Tu dirección igual quedó registrada y el depósito confirma la ubicación antes de salir.
      </div>
    );
  }
  return (
    <div style={{ fontFamily: "'DM Sans', sans-serif" }}>
      <div style={{ fontSize: 12.5, color: "#6b5d4e", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}>
        <span style={{ fontSize: 15 }}>📍</span> Arrastrá el pin al lugar exacto de tu casa.
      </div>
      <div style={{ position: "relative", borderRadius: 14, overflow: "hidden", border: `2px solid ${accent}` }}>
        <div ref={boxRef} style={{ width: "100%", height }} />
        {status === "loading" && (
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "#f6efe2", color: "#8a7a66", fontSize: 13 }}>
            Cargando mapa…
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PinPicker });
