import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Spin, Checkbox, Button, Typography, message } from 'antd';
import { EditOutlined, DragOutlined } from '@ant-design/icons';
import { MapContainer, CircleMarker, Popup, Marker, useMap, useMapEvents } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-cluster';
import type { Map as LeafletMap } from 'leaflet';
import L from 'leaflet';
import { useDebounce } from '@/hooks/useDebounce';

// Extend Leaflet Map type to include private animation properties
declare module 'leaflet' {
  interface Map {
    _animatingZoom?: boolean;
    _moving?: boolean;
  }
}
import { api } from '@/lib/api';
import type { Location, MapSettings, SupportLevel, Cut } from '@/types/api';
import { SUPPORT_LEVEL_LABELS, SUPPORT_LEVEL_COLORS } from '@/types/api';
import { groupLocations, getMarkerColor } from './mapUtils';
import { createLocationIcon } from './mapIcons';
import MapLegend from './MapLegend';
import MapControls from './MapControls';
import AddLocationMode from './AddLocationMode';
import MoveLocationMode from './MoveLocationMode';
import CutOverlays from './CutOverlays';
import CutOverlayControls from './CutOverlayControls';
import DynamicTileLayer from './DynamicTileLayer';
import TileLayerToggle from './TileLayerToggle';
import { getPersistedTileLayer, persistTileLayer, getTileConfig } from './tileLayers';
import 'leaflet/dist/leaflet.css';

const { Text } = Typography;

const ALL_LEVELS: (SupportLevel | 'NONE')[] = ['LEVEL_1', 'LEVEL_2', 'LEVEL_3', 'LEVEL_4', 'NONE'];

const LEVEL_FILTER_LABELS: Record<string, string> = {
  LEVEL_1: 'Strong Support',
  LEVEL_2: 'Likely Support',
  LEVEL_3: 'Unsure',
  LEVEL_4: 'Opposition',
  NONE: 'No Level',
};

const homeIcon = L.divIcon({
  html: '<div style="font-size:22px;text-align:center;line-height:30px">🏠</div>',
  iconSize: [30, 30],
  iconAnchor: [15, 15],
  className: '',
});

// Cluster icon factory for admin map
const createClusterCustomIcon = (cluster: any) => {
  const count = cluster.getChildCount();
  let size = 'small';
  if (count >= 100) size = 'large';
  else if (count >= 25) size = 'medium';

  return L.divIcon({
    html: `<div class="cluster-marker cluster-${size}"><span>${count}</span></div>`,
    className: 'custom-cluster-icon',
    iconSize: L.point(40, 40, true),
  });
};

// Static cluster configuration (extracted to prevent re-mount on zoom changes)
const STATIC_CLUSTER_CONFIG = {
  disableClusteringAtZoom: 18,
  spiderfyOnMaxZoom: false,
  showCoverageOnHover: false,
  zoomToBoundsOnClick: true,
  animate: true,
  animateAddingMarkers: false,
  removeOutsideVisibleBounds: true,
  chunkedLoading: true,
};

interface Props {
  locations: Location[];
  loading: boolean;
  onEditLocation: (location: Location) => void;
  onAddLocationAtPoint?: (lat: number, lng: number) => void;
  onMoveLocation?: (id: string, lat: number, lng: number) => void;
  onRefresh?: () => void;
  onMapMove?: (map: LeafletMap) => void;
  visible: boolean;
}

function InvalidateSizeOnVisible({ visible }: { visible: boolean }) {
  const map = useMap();
  useEffect(() => {
    if (visible) {
      const timer = setTimeout(() => map.invalidateSize(), 100);
      return () => clearTimeout(timer);
    }
  }, [visible, map]);
  return null;
}

function FullscreenInvalidator() {
  const map = useMap();
  useEffect(() => {
    const handler = () => {
      setTimeout(() => map.invalidateSize(), 100);
    };
    document.addEventListener('fullscreenchange', handler);
    document.addEventListener('webkitfullscreenchange', handler);
    return () => {
      document.removeEventListener('fullscreenchange', handler);
      document.removeEventListener('webkitfullscreenchange', handler);
    };
  }, [map]);
  return null;
}

function MapEventsHandler({
  setMapInstance,
  setCurrentZoom
}: {
  onMove?: (map: LeafletMap) => void;
  setMapInstance: (map: LeafletMap | null) => void;
  setCurrentZoom: (zoom: number) => void;
}) {
  const map = useMapEvents({
    moveend: () => {
      // Only trigger if not animating to prevent Leaflet state corruption
      if (!map._animatingZoom && !map._moving) {
        setMapInstance(map); // Trigger debounced callback
      }
    },
    zoomend: () => {
      setCurrentZoom(map.getZoom()); // Track current zoom
      // Wait a tick for Leaflet to finish internal zoom state updates
      setTimeout(() => {
        if (!map._animatingZoom && !map._moving) {
          setMapInstance(map);
        }
      }, 100);
    },
  });
  return null;
}

function FlyToPosition({ position }: { position: [number, number] }) {
  const map = useMap();
  useEffect(() => {
    map.flyTo(position, 17, { duration: 1.5 });
  }, [map, position]);
  return null;
}

function CenterOnSettings({ settings }: { settings: MapSettings | null }) {
  const map = useMap();

  useEffect(() => {
    if (!settings?.latitude || !settings?.longitude) return;
    const lat = parseFloat(settings.latitude);
    const lng = parseFloat(settings.longitude);
    const zoom = settings.zoom ?? 12;

    // Use setView to imperatively update map center
    map.setView([lat, lng], zoom);
  }, [map, settings]);

  return null;
}

export default function AdminMapView({
  locations,
  loading,
  onEditLocation,
  onAddLocationAtPoint,
  onMoveLocation,
  onRefresh,
  onMapMove,
  visible,
}: Props) {
  const [settings, setSettings] = useState<MapSettings | null>(null);
  const [visibleLevels, setVisibleLevels] = useState<Set<string>>(new Set(ALL_LEVELS));
  const [addMode, setAddMode] = useState(false);
  const [moveMode, setMoveMode] = useState<{ active: boolean; locationId: string | null }>({ active: false, locationId: null });
  const [showStartLocation, setShowStartLocation] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [userPosition, setUserPosition] = useState<[number, number] | null>(null);
  const [flyTo, setFlyTo] = useState<[number, number] | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [tileKey, setTileKey] = useState(getPersistedTileLayer);
  const containerRef = useRef<HTMLDivElement>(null);
  const autoRefreshRef = useRef<ReturnType<typeof setInterval>>(undefined);

  // Debounced map state for performance
  const [mapInstance, setMapInstance] = useState<LeafletMap | null>(null);
  const debouncedMapInstance = useDebounce(mapInstance, 1500);
  const [currentZoom, setCurrentZoom] = useState(12); // Default zoom, updated from map events

  // Cuts state
  const [cuts, setCuts] = useState<Cut[]>([]);
  const [visibleCutIds, setVisibleCutIds] = useState<Set<string>>(new Set());

  useEffect(() => {
    api.get<MapSettings>('/map/settings').then(({ data }) => setSettings(data)).catch(() => {});
  }, []);

  // Sync currentZoom with settings when they load
  useEffect(() => {
    if (settings?.zoom) {
      setCurrentZoom(settings.zoom);
    }
  }, [settings?.zoom]);

  // Trigger onMapMove when debounced map instance updates
  useEffect(() => {
    if (debouncedMapInstance && onMapMove) {
      onMapMove(debouncedMapInstance);
    }
  }, [debouncedMapInstance, onMapMove]);

  // Fetch cuts
  useEffect(() => {
    api.get<{ cuts: Cut[] }>('/map/cuts', { params: { limit: 100 } })
      .then(({ data }) => {
        setCuts(data.cuts);
        setVisibleCutIds(new Set(data.cuts.map((c) => c.id)));
      })
      .catch(() => {});
  }, []);

  // Auto-refresh
  useEffect(() => {
    if (autoRefresh && onRefresh) {
      autoRefreshRef.current = setInterval(onRefresh, 60000);
    }
    return () => clearInterval(autoRefreshRef.current);
  }, [autoRefresh, onRefresh]);

  // Clear user position after 30s
  useEffect(() => {
    if (userPosition) {
      const timer = setTimeout(() => setUserPosition(null), 30000);
      return () => clearTimeout(timer);
    }
  }, [userPosition]);

  // Track fullscreen state
  useEffect(() => {
    const handler = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', handler);
    document.addEventListener('webkitfullscreenchange', handler);
    return () => {
      document.removeEventListener('fullscreenchange', handler);
      document.removeEventListener('webkitfullscreenchange', handler);
    };
  }, []);

  const groups = useMemo(() => groupLocations(locations as any), [locations]);

  const filteredGroups = useMemo(() => {
    return groups.filter((g) =>
      g.location.addresses.some((addr) => {
        const level = addr.supportLevel || 'NONE';
        return visibleLevels.has(level);
      })
    );
  }, [groups, visibleLevels]);

  const center: [number, number] = settings?.latitude && settings?.longitude
    ? [parseFloat(settings.latitude), parseFloat(settings.longitude)]
    : [45.4215, -75.6972];
  const zoom = settings?.zoom ?? 12;

  const toggleLevel = (level: string, checked: boolean) => {
    setVisibleLevels((prev) => {
      const next = new Set(prev);
      if (checked) next.add(level);
      else next.delete(level);
      return next;
    });
  };

  const handleGeolocate = useCallback(() => {
    if (!navigator.geolocation) {
      message.error('Geolocation not supported');
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const p: [number, number] = [pos.coords.latitude, pos.coords.longitude];
        setUserPosition(p);
        setFlyTo(p);
        // Clear flyTo after use
        setTimeout(() => setFlyTo(null), 2000);
      },
      () => message.error('Could not get your location'),
      { enableHighAccuracy: true, timeout: 10000 }
    );
  }, []);

  const handleFullscreen = useCallback(() => {
    const el = containerRef.current;
    if (!el) return;
    if (!document.fullscreenElement) {
      const requestFs = el.requestFullscreen || (el as any).webkitRequestFullscreen;
      if (requestFs) requestFs.call(el);
    } else {
      const exitFs = document.exitFullscreen || (document as any).webkitExitFullscreen;
      if (exitFs) exitFs.call(document);
    }
  }, []);

  const handleMapClick = useCallback(
    (lat: number, lng: number) => {
      if (onAddLocationAtPoint) {
        onAddLocationAtPoint(lat, lng);
        setAddMode(false);
      }
    },
    [onAddLocationAtPoint]
  );

  const startMoveMode = useCallback((locationId: string) => {
    setMoveMode({ active: true, locationId });
    setAddMode(false);
  }, []);

  const handleConfirmMove = useCallback(
    (lat: number, lng: number) => {
      if (onMoveLocation && moveMode.locationId) {
        onMoveLocation(moveMode.locationId, lat, lng);
      }
      setMoveMode({ active: false, locationId: null });
    },
    [onMoveLocation, moveMode.locationId]
  );

  const handleCancelMove = useCallback(() => {
    setMoveMode({ active: false, locationId: null });
  }, []);

  const toggleCut = useCallback((id: string) => {
    setVisibleCutIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }, []);

  // Memoized cluster config with zoom-aware radius
  const clusterConfig = useMemo(() => {
    // Zoom-aware cluster radius (30/50/80px like volunteer map)
    const maxClusterRadius = currentZoom >= 15 ? 30 : currentZoom >= 12 ? 50 : 80;

    return {
      ...STATIC_CLUSTER_CONFIG,
      maxClusterRadius,
      iconCreateFunction: createClusterCustomIcon,
    };
  }, [currentZoom]);

  // Memoized marker rendering to prevent unnecessary re-renders
  const markers = useMemo(() => {
    return filteredGroups.map((group, idx) => {
      const color = getMarkerColor(group.dominantLevel);
      const icon = createLocationIcon(color, group.isMultiUnit);

      return (
        <Marker
          key={`${group.location.id}-${idx}`}
          position={[group.latitude, group.longitude]}
          icon={icon}
        >
          <Popup>
            <div style={{ minWidth: 200, maxWidth: 300 }}>
              {group.isMultiUnit ? (
                // Multi-unit building display
                <>
                  <div style={{ marginBottom: 8, paddingBottom: 8, borderBottom: '2px solid #a02c8d' }}>
                    <div style={{ fontWeight: 600, fontSize: 14, color: '#a02c8d' }}>
                      🏢 {group.location.address || 'Multi-Unit Building'}
                    </div>
                    <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
                      {group.location.addresses.length} units
                    </div>
                  </div>
                  {group.location.addresses
                    .sort((a, b) => {
                      const aUnit = a.unitNumber || '';
                      const bUnit = b.unitNumber || '';
                      return aUnit.localeCompare(bUnit, undefined, { numeric: true });
                    })
                    .map((addr, i) => {
                      const name = [addr.firstName, addr.lastName].filter(Boolean).join(' ');
                      return (
                        <div
                          key={addr.id}
                          style={{
                            marginBottom: i < group.location.addresses.length - 1 ? 8 : 0,
                            paddingBottom: i < group.location.addresses.length - 1 ? 8 : 0,
                            borderBottom: i < group.location.addresses.length - 1 ? '1px solid rgba(255,255,255,0.1)' : 'none',
                          }}
                        >
                          {addr.unitNumber && (
                            <div style={{ fontSize: 12, fontWeight: 600, color: '#555', marginBottom: 2 }}>
                              Unit {addr.unitNumber}
                            </div>
                          )}
                          {name && <div style={{ fontSize: 12, marginBottom: 2 }}>{name}</div>}
                          {addr.email && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>{addr.email}</div>}
                          {addr.phone && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>{addr.phone}</div>}
                          {addr.supportLevel && (
                            <div style={{ fontSize: 12, marginTop: 4 }}>
                              <span
                                style={{
                                  display: 'inline-block',
                                  width: 8,
                                  height: 8,
                                  borderRadius: '50%',
                                  backgroundColor: getMarkerColor(addr.supportLevel),
                                  marginRight: 4,
                                }}
                              />
                              {SUPPORT_LEVEL_LABELS[addr.supportLevel]}
                            </div>
                          )}
                          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>
                            {addr.sign && <>Sign{addr.signSize ? ` (${addr.signSize})` : ''} &middot; </>}
                            {group.location.geocodeConfidence != null && <>Confidence: {group.location.geocodeConfidence}%</>}
                          </div>
                          {addr.notes && (
                            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 4, fontStyle: 'italic' }}>
                              {addr.notes}
                            </div>
                          )}
                          <div style={{ marginTop: 4, display: 'flex', gap: 8 }}>
                            <Button
                              type="link"
                              size="small"
                              icon={<EditOutlined />}
                              onClick={(e) => {
                                e.stopPropagation();
                                onEditLocation(group.location);
                              }}
                              style={{ padding: 0, height: 'auto', fontSize: 12 }}
                            >
                              Edit
                            </Button>
                            {onMoveLocation && (
                              <Button
                                type="link"
                                size="small"
                                icon={<DragOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  startMoveMode(group.location.id);
                                }}
                                style={{ padding: 0, height: 'auto', fontSize: 12 }}
                              >
                                Move
                              </Button>
                            )}
                          </div>
                        </div>
                      );
                    })}
                </>
              ) : (
                // Single unit display
                <>
                  {(() => {
                    const addr = group.location.addresses[0];
                    const name = addr ? [addr.firstName, addr.lastName].filter(Boolean).join(' ') : '';
                    return (
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>
                          {group.location.address || 'Unknown address'}
                          {addr?.unitNumber && <Text type="secondary" style={{ fontSize: 12 }}> Unit {addr.unitNumber}</Text>}
                        </div>
                        {name && <div style={{ fontSize: 12, marginBottom: 2 }}>{name}</div>}
                        {addr?.email && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>{addr.email}</div>}
                        {addr?.phone && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>{addr.phone}</div>}
                        {addr?.supportLevel && (
                          <div style={{ fontSize: 12, marginTop: 4 }}>
                            <span
                              style={{
                                display: 'inline-block',
                                width: 8,
                                height: 8,
                                borderRadius: '50%',
                                backgroundColor: getMarkerColor(addr.supportLevel),
                                marginRight: 4,
                              }}
                            />
                            {SUPPORT_LEVEL_LABELS[addr.supportLevel]}
                          </div>
                        )}
                        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>
                          {addr?.sign && <>Sign{addr.signSize ? ` (${addr.signSize})` : ''} &middot; </>}
                          {group.location.geocodeConfidence != null && <>Confidence: {group.location.geocodeConfidence}%</>}
                        </div>
                        {addr?.notes && (
                          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 4, fontStyle: 'italic' }}>
                            {addr.notes}
                          </div>
                        )}
                        <div style={{ marginTop: 4, display: 'flex', gap: 8 }}>
                          <Button
                            type="link"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              onEditLocation(group.location);
                            }}
                            style={{ padding: 0, height: 'auto', fontSize: 12 }}
                          >
                            Edit
                          </Button>
                          {onMoveLocation && (
                            <Button
                              type="link"
                              size="small"
                              icon={<DragOutlined />}
                              onClick={(e) => {
                                e.stopPropagation();
                                startMoveMode(group.location.id);
                              }}
                              style={{ padding: 0, height: 'auto', fontSize: 12 }}
                            >
                              Move
                            </Button>
                          )}
                        </div>
                      </div>
                    );
                  })()}
                </>
              )}
            </div>
          </Popup>
        </Marker>
      );
    });
  }, [filteredGroups, onEditLocation, onMoveLocation, startMoveMode]);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div
      ref={containerRef}
      id="admin-map-container"
      style={{ position: 'relative', width: '100%', height: 'calc(100vh - 240px)', minHeight: 500, background: '#1a1025' }}
    >
      {/* Support level filter overlay */}
      <div
        role="group"
        aria-label="Support level filter"
        style={{
          position: 'absolute',
          top: 10,
          left: 70,
          zIndex: 1000,
          background: 'rgba(26, 16, 37, 0.92)',
          borderRadius: 8,
          padding: '8px 12px',
          backdropFilter: 'blur(8px)',
          border: '1px solid rgba(255,255,255,0.12)',
          maxWidth: 160,
        }}
      >
        <div style={{ fontSize: 11, fontWeight: 600, color: 'rgba(255,255,255,0.65)', marginBottom: 4 }}>
          Filter
        </div>
        {ALL_LEVELS.map((level) => (
          <div key={level} style={{ marginBottom: 2 }}>
            <Checkbox
              checked={visibleLevels.has(level)}
              onChange={(e) => toggleLevel(level, e.target.checked)}
              style={{ fontSize: 12 }}
            >
              <span style={{ color: level === 'NONE' ? '#3498db' : SUPPORT_LEVEL_COLORS[level as SupportLevel] }}>
                {LEVEL_FILTER_LABELS[level]}
              </span>
            </Checkbox>
          </div>
        ))}
      </div>

      {/* Mode indicators */}
      {(addMode || moveMode.active) && (
        <div
          style={{
            position: 'absolute',
            top: 10,
            left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 1001,
            background: addMode ? 'rgba(157, 78, 221, 0.9)' : 'rgba(255, 77, 79, 0.9)',
            borderRadius: 8,
            padding: '6px 16px',
            color: '#fff',
            fontWeight: 600,
            fontSize: 13,
          }}
        >
          {addMode ? 'Click map to add location' : 'Click map to move location'}
        </div>
      )}

      <MapControls
        addMode={addMode}
        onToggleAddMode={() => {
          setAddMode((p) => !p);
          if (!addMode) setMoveMode({ active: false, locationId: null });
        }}
        moveMode={moveMode.active}
        onCancelMoveMode={handleCancelMove}
        showStartLocation={showStartLocation}
        onToggleStartLocation={() => setShowStartLocation((p) => !p)}
        isFullscreen={isFullscreen}
        onToggleFullscreen={handleFullscreen}
        onGeolocate={handleGeolocate}
        onRefresh={() => onRefresh?.()}
        autoRefresh={autoRefresh}
        onToggleAutoRefresh={() => setAutoRefresh((p) => !p)}
      />

      <style>{`
        .admin-map .leaflet-popup-content-wrapper {
          background: #1a1025;
          color: rgba(255,255,255,0.85);
          border: 1px solid rgba(255,255,255,0.12);
          border-radius: 8px;
        }
        .admin-map .leaflet-popup-tip {
          background: #1a1025;
        }
        .admin-map .leaflet-popup-content {
          margin: 10px 14px;
        }
        .custom-cluster-icon {
          background: transparent;
        }
        .cluster-marker {
          background-color: rgba(157, 78, 221, 0.8);
          border: 2px solid #fff;
          border-radius: 50%;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 14px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.3);
          width: 40px;
          height: 40px;
        }
        .cluster-marker.cluster-medium {
          width: 50px;
          height: 50px;
          font-size: 16px;
          background-color: rgba(157, 78, 221, 0.9);
        }
        .cluster-marker.cluster-large {
          width: 60px;
          height: 60px;
          font-size: 18px;
          background-color: rgba(157, 78, 221, 1);
        }
        .location-icon-marker {
          background: transparent;
          border: none;
        }
      `}</style>

      <MapContainer
        center={center}
        zoom={zoom}
        style={{ width: '100%', height: '100%', borderRadius: 8 }}
        scrollWheelZoom={true}
        className="admin-map"
      >
        <InvalidateSizeOnVisible visible={visible} />
        <FullscreenInvalidator />
        <CenterOnSettings settings={settings} />
        <MapEventsHandler
          onMove={onMapMove}
          setMapInstance={setMapInstance}
          setCurrentZoom={setCurrentZoom}
        />
        {flyTo && <FlyToPosition position={flyTo} />}
        <DynamicTileLayer config={getTileConfig(tileKey)} />

        {/* Cut overlays (render beneath location markers) */}
        <CutOverlays cuts={cuts} visibleCutIds={visibleCutIds} />

        {/* Add location mode */}
        <AddLocationMode active={addMode && !moveMode.active} onMapClick={handleMapClick} />

        {/* Move location mode */}
        <MoveLocationMode
          active={moveMode.active}
          onConfirmMove={handleConfirmMove}
          onCancel={handleCancelMove}
        />

        {/* Start location marker */}
        {showStartLocation && settings?.latitude && settings?.longitude && (
          <Marker
            position={[parseFloat(settings.latitude), parseFloat(settings.longitude)]}
            icon={homeIcon}
          />
        )}

        {/* User position */}
        {userPosition && (
          <CircleMarker
            center={userPosition}
            radius={8}
            pathOptions={{
              fillColor: '#2196F3',
              fillOpacity: 0.9,
              color: '#fff',
              weight: 2,
              opacity: 1,
            }}
          />
        )}

        {/* Location markers with clustering */}
        <MarkerClusterGroup
          key={currentZoom >= 18 ? 'unclustered' : 'clustered'}
          {...clusterConfig}
        >
          {markers}
        </MarkerClusterGroup>
      </MapContainer>

      <MapLegend variant="admin" />

      <TileLayerToggle
        activeKey={tileKey}
        onChange={(key) => { setTileKey(key); persistTileLayer(key); }}
        position="bottom-left"
      />

      {/* Cut overlay controls */}
      {cuts.length > 0 && (
        <CutOverlayControls
          cuts={cuts}
          visibleCutIds={visibleCutIds}
          onToggleCut={toggleCut}
          variant="admin"
          style={{ top: 180, left: 10, bottom: 'auto' }}
        />
      )}
    </div>
  );
}
