// Mappa Calabria — Leaflet.js + CartoDB Voyager tiles
// Coordinate: x = 100 + (lon-15.6)*250  →  lon = (x-100)/250 + 15.6
//             y = 80  + (40.15-lat)*278  →  lat = 40.15 - (y-80)/278

const KIND_DEFS = [
  { key: "citta",       label: "Città",       color: "#1c1612" },
  { key: "costa",       label: "Costa",       color: "#1a5c7a" },
  { key: "parco",       label: "Parchi",      color: "#2d6a4f" },
  { key: "archeologia", label: "Archeologia", color: "#9b5c1a" },
  { key: "borgo",       label: "Borghi",      color: "#7a2e2e" },
  { key: "spiaggia",    label: "Spiagge",     color: "#0077a8" },
  { key: "alture",      label: "Alture",      color: "#4a6741" },
];

function getKindColor(kind) {
  return (KIND_DEFS.find(k => k.key === kind) || {}).color || "#6b5f4e";
}

function ptToLatLng(pt) {
  return [
    40.15 - (pt.y - 80) / 278,
    (pt.x - 100) / 250 + 15.6,
  ];
}

function CalabriaMap() {
  const [activeKind, setActiveKind] = useState("ALL");
  const [hoveredPt,  setHoveredPt]  = useState(null);
  const mobile = useMobile();

  const mapDivRef     = useRef(null);
  const mapRef        = useRef(null);
  const markersRef    = useRef({});

  // ── Inizializza Leaflet una sola volta ──
  useEffect(() => {
    if (mapRef.current) return;

    const map = L.map(mapDivRef.current, {
      center: [38.85, 16.55],
      zoom: 8,
      scrollWheelZoom: false,
      zoomControl: false,
      attributionControl: true,
    });

    L.control.zoom({ position: "bottomright" }).addTo(map);

    // CartoDB Voyager — palette calda, ottimo su desktop e mobile
    L.tileLayer(
      "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png",
      {
        attribution:
          '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com">CARTO</a>',
        subdomains: "abcd",
        maxZoom: 17,
      }
    ).addTo(map);

    // ── Marker per ogni luogo ──
    MAP_POINTS.forEach(pt => {
      const latlng  = ptToLatLng(pt);
      const color   = getKindColor(pt.kind);
      const isCitta = pt.kind === "citta";
      const r       = isCitta ? 9 : 7;

      const circle = L.circleMarker(latlng, {
        radius:      r,
        fillColor:   color,
        color:       "#fff",
        weight:      2,
        opacity:     1,
        fillOpacity: 0.9,
      }).addTo(map);

      // Tooltip — permanente per le città, al hover per gli altri
      circle.bindTooltip(pt.name, {
        permanent:  isCitta,
        direction:  "right",
        offset:     [10, 0],
        className:  "cal-tip",
        opacity:    1,
      });

      circle.on("mouseover", function () {
        setHoveredPt(pt);
        this.setRadius(isCitta ? 13 : 11);
        if (!isCitta) this.openTooltip();
      });
      circle.on("mouseout", function () {
        setHoveredPt(null);
        this.setRadius(r);
        if (!isCitta) this.closeTooltip();
      });

      markersRef.current[pt.id] = { circle, isCitta, r };
    });

    mapRef.current = map;
  }, []);

  // ── Aggiorna opacità marker al cambio filtro ──
  useEffect(() => {
    if (!mapRef.current) return;
    Object.entries(markersRef.current).forEach(([id, { circle }]) => {
      const pt      = MAP_POINTS.find(p => p.id === id);
      const visible = activeKind === "ALL" || pt?.kind === activeKind;
      circle.setStyle({
        fillOpacity: visible ? 0.9 : 0.06,
        opacity:     visible ? 1   : 0.06,
      });
    });
  }, [activeKind]);

  const toggleKind   = (key) => setActiveKind(prev => prev === key ? "ALL" : key);
  const visibleCount = activeKind === "ALL"
    ? MAP_POINTS.length
    : MAP_POINTS.filter(p => p.kind === activeKind).length;

  return (
    <section id="mappa" style={{
      padding: "var(--section-pad) 0",
      borderTop: "1px solid var(--line)",
      background: "var(--paper-2)",
    }}>
      <div className="container">
        <SectionHeader kicker="Esplora la cartina" title="La Calabria, punto per punto" />

        <div style={{
          display: "grid",
          gridTemplateColumns: mobile ? "1fr" : "300px 1fr",
          gap: mobile ? 24 : 40,
          alignItems: "start",
        }}>

          {/* ── Pannello sinistro ── */}
          <div style={{
            padding: 24,
            background: "var(--paper)",
            border: "1px solid var(--line)",
          }}>
            {hoveredPt ? (
              <>
                <Eyebrow>
                  {(KIND_DEFS.find(k => k.key === hoveredPt.kind) || {}).label || hoveredPt.kind}
                </Eyebrow>
                <h3 style={{
                  fontFamily: "var(--font-display)", fontSize: 36, fontWeight: 500,
                  margin: "12px 0 10px", letterSpacing: "-0.01em", lineHeight: 1.1,
                }}>{hoveredPt.name}</h3>
                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)",
                  letterSpacing: "0.1em", textTransform: "uppercase",
                }}>
                  Provincia di {(PROVINCES.find(p => p.code === hoveredPt.province) || {}).name}
                </div>
                <a href="#" style={{
                  marginTop: 20, display: "inline-flex", alignItems: "center", gap: 8,
                  fontSize: 12, letterSpacing: "0.06em", textTransform: "uppercase",
                  paddingBottom: 3, borderBottom: "1px solid currentColor",
                }}>
                  Scopri {hoveredPt.name} <IconArrow />
                </a>
              </>
            ) : (
              <>
                <Eyebrow>Esplora {visibleCount} luoghi</Eyebrow>
                <h3 style={{
                  fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 500,
                  margin: "12px 0 14px", letterSpacing: "-0.01em", lineHeight: 1.2,
                }}>
                  Passa sopra un punto della mappa.
                </h3>
                <p style={{
                  fontSize: 14, lineHeight: 1.6, color: "var(--muted)", margin: 0,
                }}>
                  Filtra per tipologia o passa il cursore su un marker per scoprire il luogo.
                </p>
              </>
            )}

            {/* ── Filtri tipologia ── */}
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 1fr",
              gap: 2, marginTop: 20, paddingTop: 16,
              borderTop: "1px solid var(--line)",
            }}>
              {KIND_DEFS.map(kind => {
                const isActive = activeKind === kind.key;
                return (
                  <button
                    key={kind.key}
                    onClick={() => toggleKind(kind.key)}
                    style={{
                      display: "flex", alignItems: "center", gap: 9,
                      fontSize: 11, fontFamily: "var(--font-mono)",
                      letterSpacing: "0.06em", textTransform: "uppercase",
                      color:      isActive ? "var(--ink)"    : "var(--muted)",
                      fontWeight: isActive ? 600             : 400,
                      background: isActive ? "var(--paper-2)": "transparent",
                      border: "none", textAlign: "left",
                      padding: "8px 10px", cursor: "pointer", borderRadius: 2,
                      transition: "color .2s, background .2s",
                    }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: 999,
                      background: kind.color, flexShrink: 0,
                      opacity: isActive ? 1 : 0.6,
                    }} />
                    {kind.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* ── Contenitore mappa Leaflet ── */}
          <div
            ref={mapDivRef}
            style={{
              height: mobile ? 320 : 560,
              border: "1px solid var(--line)",
              borderRadius: 2,
              overflow: "hidden",
              zIndex: 0,
            }}
          />
        </div>
      </div>
    </section>
  );
}
window.CalabriaMap = CalabriaMap;
