"use client";
import { useEffect, useState } from "react";
import { MapContainer, TileLayer, GeoJSON, useMap, Marker, Popup } from "react-leaflet";
import L from 'leaflet';
import "leaflet/dist/leaflet.css";

// Icono para el marcador GPS (Punto azul)
const iconGPS = new L.Icon({
  iconUrl: 'https://cdn-icons-png.flaticon.com/512/684/684908.png',
  iconSize: [35, 35],
  iconAnchor: [17, 35],
});

// Componente para mover la cámara al cambiar de sección o posición
function ChangeView({ center }: { center: [number, number] }) {
  const map = useMap();
  useEffect(() => {
    if (center && center[0] && center[1]) {
      map.setView(center, 15);
    }
  }, [center, map]);
  return null;
}

export default function MapaSeccion({ seccionElectoral }: { seccionElectoral: number }) {
  const [geojsonData, setGeojsonData] = useState<any>(null);
  const [position, setPosition] = useState<[number, number] | null>(null);
  const [loading, setLoading] = useState(true);

  // 1. Cargar coordenadas desde tu API
  useEffect(() => {
    if (seccionElectoral) {
      setLoading(true);
      fetch(`/api/maps?seccion=${seccionElectoral}`)
        .then((res) => res.json())
        .then((data) => {
          setGeojsonData(data);
          setLoading(false);
        })
        .catch(() => setLoading(false));
    }
  }, [seccionElectoral]);

  // 2. Función del botón "¿Dónde estoy?"
  const localizarMe = () => {
    if (!navigator.geolocation) return alert("GPS no soportado");
    navigator.geolocation.getCurrentPosition(
      (pos) => setPosition([pos.coords.latitude, pos.coords.longitude]),
      () => alert("Activa el GPS de tu dispositivo")
    );
  };

  if (loading) return <div className="h-[250px] flex items-center justify-center text-[10px] font-black uppercase text-gray-500 animate-pulse">Sincronizando...</div>;

  // --- LÓGICA DE CENTRADO CORREGIDA PARA MULTIPOLYGON ---
  let mapCenter: [number, number] = [18.845, -99.184]; // Centro de Zapata por defecto
  
  if (geojsonData?.features?.length > 0) {
    const geometry = geojsonData.features[0].geometry;
    let coords = null;

    if (geometry.type === "MultiPolygon") {
      // Estructura: [Polygon][Ring][Point] -> Necesitamos el primer punto
      coords = geometry.coordinates[0][0][0];
    } else if (geometry.type === "Polygon") {
      // Estructura: [Ring][Point]
      coords = geometry.coordinates[0][0];
    }

    if (coords && coords[1] && coords[0]) {
      mapCenter = [coords[1], coords[0]];
    }
  }

  return (
    <div className="flex flex-col gap-4 w-full">
      <button 
        onClick={localizarMe}
        className="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-4 rounded-2xl shadow-lg transition-all flex items-center justify-center gap-2 text-[10px] uppercase italic tracking-widest"
      >
        📍 ¿DÓNDE ESTOY?
      </button>

      <div className="h-[300px] w-full rounded-[2rem] overflow-hidden border border-gray-800 relative shadow-2xl">
        <MapContainer
          center={mapCenter}
          zoom={15}
          style={{ height: "100%", width: "100%" }}
          zoomControl={false}
        >
          <ChangeView center={position || mapCenter} />
          
          <TileLayer
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='&copy; OpenStreetMap'
          />

          {geojsonData && (
            <GeoJSON
              key={seccionElectoral} 
              data={geojsonData}
              style={{
                color: "#ec4899",
                weight: 4,
                fillColor: "#ec4899",
                fillOpacity: 0.25,
              }}
            />
          )}

          {position && (
            <Marker position={position} icon={iconGPS}>
              <Popup>Estás aquí</Popup>
            </Marker>
          )}
        </MapContainer>
      </div>
    </div>
  );
}