"use client";
import L from "leaflet";
import { useEffect } from "react";
import { Circle, MapContainer, Marker, useMap } from "react-leaflet";

import type { Musician } from "@/lib/types";
import { MapLibreLayer } from "./MapLibreLayer";

/** Pin del músico: gota teal con el emoji del instrumento. divIcon evita el bug de assets de Leaflet. */
function musicianIcon(emoji: string, active: boolean) {
  return L.divIcon({
    className: "",
    html: `<div style="
      display:grid;place-items:center;width:36px;height:36px;border-radius:50% 50% 50% 0;
      transform:rotate(-45deg);
      background:${active ? "#06b6d4" : "#ffffff"};
      border:2px solid ${active ? "#22d3ee" : "#06b6d4"};
      box-shadow:0 6px 14px -3px rgba(2,8,20,.4);">
        <span style="transform:rotate(45deg);font-size:16px;">${emoji}</span>
      </div>`,
    iconSize: [36, 36],
    iconAnchor: [18, 36],
  });
}

const userIcon = L.divIcon({
  className: "",
  html: `<div style="width:18px;height:18px;border-radius:50%;background:#2563eb;
    border:3px solid #fff;box-shadow:0 0 0 7px rgba(37,99,235,.18);"></div>`,
  iconSize: [18, 18],
  iconAnchor: [9, 9],
});

/** Recentra el mapa cuando cambia el punto del usuario. */
function Recenter({ center }: { center: [number, number] }) {
  const map = useMap();
  useEffect(() => {
    map.setView(center);
  }, [center, map]);
  return null;
}

interface Props {
  center: [number, number];
  musicians: Musician[];
  emojiFor: (m: Musician) => string;
  radiusKm?: number;
  activeId?: number | null;
  night?: boolean;
  onMarkerClick?: (m: Musician) => void;
}

// Estilos vectoriales limpios estilo Uber (CARTO GL, sin API key): Positron de día, Dark Matter de noche.
const STYLE_DAY = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json";
const STYLE_NIGHT = "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json";

export default function MapView({
  center,
  musicians,
  emojiFor,
  radiusKm,
  activeId,
  night,
  onMarkerClick,
}: Props) {
  return (
    <MapContainer center={center} zoom={13} scrollWheelZoom className="h-full w-full" attributionControl>
      <MapLibreLayer style={night ? STYLE_NIGHT : STYLE_DAY} />
      <Recenter center={center} />

      {radiusKm ? (
        <Circle
          center={center}
          radius={radiusKm * 1000}
          pathOptions={{ color: "#06b6d4", weight: 1.5, dashArray: "4 4", fillColor: "#06b6d4", fillOpacity: 0.06 }}
        />
      ) : null}

      <Marker position={center} icon={userIcon} />

      {musicians.map((m) =>
        m.lat != null && m.lng != null ? (
          <Marker
            key={m.id}
            position={[m.lat, m.lng]}
            icon={musicianIcon(emojiFor(m), m.id === activeId)}
            eventHandlers={{ click: () => onMarkerClick?.(m) }}
          />
        ) : null,
      )}
    </MapContainer>
  );
}
