import { useCallback, useRef, useEffect, useState, useMemo, memo } from 'react';
import type { CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
import { Map as MapGL, ScaleControl } from 'react-map-gl/maplibre';
import type { MapRef } from 'react-map-gl/maplibre';
import 'maplibre-gl/dist/maplibre-gl.css';
import type {
  HexagonData,
  PostcodeFeature,
  PostcodeGeometry,
  ViewState,
  ViewChangeParams,
  POI,
  FeatureMeta,
  Bounds,
  MapFlyToOptions,
  ActualListing,
} from '../../types';

import {
  zoomToResolution,
  getVisibleBoundsFromViewState,
  getBoundsWithBottomScreenInset,
  getMapStyle,
  getMapDataBeforeId,
  getMapCenterForTargetScreenPoint,
} from '../../lib/map-utils';
import { MAP_MIN_ZOOM, MAP_BOUNDS, POI_AUTO_CARD_ZOOM_THRESHOLD } from '../../lib/consts';
import type { SearchedLocation } from './LocationSearch';
import { LogoIcon } from '../ui/icons/LogoIcon';
import { CloseIcon } from '../ui/icons/CloseIcon';
import type { FeatureFilters } from '../../types';
import { useDeckLayers } from '../../hooks/useDeckLayers';
import { useMapCardLayout } from '../../hooks/useMapCardLayout';
import type { TravelTimeEntry } from '../../hooks/useTravelTime';
import { type OverlayId } from '../../lib/overlays';
import { CRIME_TYPE_VALUES } from '../../lib/crime-types';
import type { BasemapId } from '../../lib/basemaps';
import { DeckOverlay } from './DeckOverlay';
import { OverlayTileLayers } from './OverlayTileLayers';
import { MapTopCards } from './MapTopCards';
import { PoiPopupCardContent } from './PoiPopupCard';
import { ListingClusterPopupContent, ListingPopupSingleContent } from './ListingPopups';
import { HoverCardOverlay } from './HoverCardOverlay';

interface MapProps {
  data: HexagonData[];
  postcodeData: PostcodeFeature[];
  usePostcodeView: boolean;
  pois: POI[];
  activeOverlays?: Set<OverlayId>;
  activeCrimeTypes?: Set<string>;
  basemap?: BasemapId;
  colorOpacity?: number;
  actualListings?: ActualListing[];
  onViewChange: (params: ViewChangeParams) => void;
  viewFeature: string | null;
  colorRange: [number, number] | null;
  filterRange: [number, number] | null;
  viewSource: 'drag' | 'eye' | null;
  onCancelPin: () => void;
  onResetPreviewScale?: () => void;
  canResetPreviewScale?: boolean;
  features: FeatureMeta[];
  selectedHexagonId: string | null;
  hoveredHexagonId: string | null;
  onHexagonClick: (id: string, isPostcode?: boolean, geometry?: PostcodeGeometry) => void;
  onHexagonHover: (h3: string | null, x?: number, y?: number) => void;
  initialViewState: ViewState;
  flyToRef?: React.MutableRefObject<
    ((lat: number, lng: number, zoom: number, options?: MapFlyToOptions) => void) | null
  >;
  theme?: 'light' | 'dark';
  screenshotMode?: boolean;
  ogMode?: boolean;
  filters?: FeatureFilters;
  selectedPostcodeGeometry?: PostcodeGeometry | null;
  onLocationSearched?: (location: SearchedLocation | null) => void;
  onCurrentLocationFound?: (lat: number, lng: number) => void;
  currentLocation?: { lat: number; lng: number } | null;
  bounds?: Bounds | null;
  hideLegend?: boolean;
  hideLocationSearch?: boolean;
  hideTopCardsWhenNarrow?: boolean;
  /** Space (px) to keep clear on the right of the top-card overlay so the
   * search bar doesn't run under controls anchored there (mobile buttons). */
  topCardsRightInset?: number;
  travelTimeEntries?: TravelTimeEntry[];
  densityLabel?: string;
  totalCount?: number;
  bottomScreenInset?: number;
}

const EMPTY_TRAVEL_ENTRIES: TravelTimeEntry[] = [];
const EMPTY_ACTUAL_LISTINGS: ActualListing[] = [];
const EMPTY_OVERLAYS = new Set<OverlayId>();
const ALL_CRIME_TYPES = new Set<string>(CRIME_TYPE_VALUES);

interface Dimensions {
  width: number;
  height: number;
}

type MapContainerStyle = CSSProperties & {
  '--map-mobile-bottom-inset'?: string;
};

function resolveInset(
  pixelValue: number | undefined,
  ratioValue: number | undefined,
  size: number
) {
  return Math.max(0, (pixelValue ?? 0) + (ratioValue ?? 0) * size);
}

function clamp(value: number, min: number, max: number) {
  return Math.min(max, Math.max(min, value));
}

function getMapRelativeVisibleAreaCenter(dimensions: Dimensions, options?: MapFlyToOptions) {
  const area = options?.visibleArea;
  const leftInset = resolveInset(area?.left, area?.leftRatio, dimensions.width);
  const rightInset = resolveInset(area?.right, area?.rightRatio, dimensions.width);
  const topInset = resolveInset(area?.top, area?.topRatio, dimensions.height);
  const bottomInset = resolveInset(area?.bottom, area?.bottomRatio, dimensions.height);

  const left = Math.min(dimensions.width, leftInset);
  const right = Math.max(left, dimensions.width - Math.min(dimensions.width, rightInset));
  const top = Math.min(dimensions.height, topInset);
  const bottom = Math.max(top, dimensions.height - Math.min(dimensions.height, bottomInset));

  return {
    x: (left + right) / 2,
    y: (top + bottom) / 2,
  };
}

function getViewportRelativeVisibleAreaCenter(
  dimensions: Dimensions,
  container: HTMLDivElement | null,
  options?: MapFlyToOptions
) {
  const area = options?.visibleViewportArea;
  if (!area || !container) return null;

  const rect = container.getBoundingClientRect();
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;
  const viewportLeft = resolveInset(area.left, area.leftRatio, viewportWidth);
  const viewportRight = viewportWidth - resolveInset(area.right, area.rightRatio, viewportWidth);
  const viewportTop = resolveInset(area.top, area.topRatio, viewportHeight);
  const viewportBottom =
    viewportHeight - resolveInset(area.bottom, area.bottomRatio, viewportHeight);

  const left = clamp(viewportLeft - rect.left, 0, dimensions.width);
  const right = clamp(viewportRight - rect.left, left, dimensions.width);
  const top = clamp(viewportTop - rect.top, 0, dimensions.height);
  const bottom = clamp(viewportBottom - rect.top, top, dimensions.height);

  return {
    x: (left + right) / 2,
    y: (top + bottom) / 2,
  };
}

function getRenderedViewState(map: MapRef | null): ViewState | null {
  if (!map) return null;

  const center = map.getCenter();
  return {
    longitude: center.lng,
    latitude: center.lat,
    zoom: map.getZoom(),
    pitch: map.getPitch(),
    bearing: map.getBearing(),
  };
}

function getRenderedVisibleCenter(
  map: MapRef | null,
  dimensions: Dimensions,
  bottomScreenInset: number
): Pick<ViewState, 'latitude' | 'longitude'> | null {
  if (!map || dimensions.width <= 0 || dimensions.height <= 0) return null;

  const visibleBottomInset = clamp(bottomScreenInset, 0, dimensions.height);
  const visibleCenterY = (dimensions.height - visibleBottomInset) / 2;
  const center = map.unproject([dimensions.width / 2, visibleCenterY]);

  return {
    longitude: center.lng,
    latitude: center.lat,
  };
}

export default memo(function Map({
  data,
  postcodeData,
  usePostcodeView,
  pois,
  activeOverlays = EMPTY_OVERLAYS,
  activeCrimeTypes = ALL_CRIME_TYPES,
  basemap = 'standard',
  colorOpacity = 1,
  actualListings = EMPTY_ACTUAL_LISTINGS,
  onViewChange,
  viewFeature,
  colorRange,
  filterRange,
  viewSource,
  onCancelPin,
  onResetPreviewScale,
  canResetPreviewScale = false,
  features,
  selectedHexagonId,
  hoveredHexagonId,
  onHexagonClick,
  onHexagonHover,
  initialViewState,
  flyToRef,
  theme = 'light',
  screenshotMode = false,
  ogMode = false,
  filters = {},
  selectedPostcodeGeometry,
  onLocationSearched,
  onCurrentLocationFound,
  currentLocation,
  bounds: viewportBounds,
  hideLegend = false,
  hideLocationSearch = false,
  hideTopCardsWhenNarrow = false,
  topCardsRightInset = 0,
  travelTimeEntries = EMPTY_TRAVEL_ENTRIES,
  densityLabel: densityLabelProp,
  totalCount: totalCountProp,
  bottomScreenInset = 0,
}: MapProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<MapRef | null>(null);
  const { t } = useTranslation();
  const densityLabel = densityLabelProp ?? t('mapLegend.numberOfProperties');
  const [internalViewState, setInternalViewState] = useState<ViewState>(initialViewState);
  const [dimensions, setDimensions] = useState<Dimensions>({ width: 0, height: 0 });
  const [mapReady, setMapReady] = useState(false);

  // In screenshot mode, use the prop directly for instant updates (no async lag)
  const viewState = screenshotMode ? initialViewState : internalViewState;

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    let resizeTimer: ReturnType<typeof setTimeout> | null = null;
    let initialized = false;
    const observer = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect;
      if (width > 0 && height > 0) {
        if (!initialized) {
          initialized = true;
          setDimensions({ width, height });
        } else {
          if (resizeTimer) clearTimeout(resizeTimer);
          resizeTimer = setTimeout(() => setDimensions({ width, height }), 150);
        }
      }
    });

    observer.observe(container);
    return () => {
      observer.disconnect();
      if (resizeTimer) clearTimeout(resizeTimer);
    };
  }, []);

  useEffect(() => {
    if (dimensions.width === 0 || dimensions.height === 0) return;

    let frame = 0;
    const emit = () => {
      const renderedViewState = getRenderedViewState(mapRef.current);
      // mapRef can be null on the very first effect run if MapLibre hasn't
      // finished mounting; retry next frame so the initial bounds always reach
      // the data hook.
      if (!renderedViewState) {
        frame = window.requestAnimationFrame(emit);
        return;
      }
      const bounds = getVisibleBoundsFromViewState(
        renderedViewState,
        dimensions.width,
        dimensions.height,
        bottomScreenInset
      );
      const visibleBounds = bounds;
      const resolution = zoomToResolution(renderedViewState.zoom);
      const renderedVisibleCenter =
        getRenderedVisibleCenter(mapRef.current, dimensions, bottomScreenInset) ??
        renderedViewState;

      onViewChange({
        resolution,
        bounds,
        visibleBounds,
        zoom: renderedViewState.zoom,
        latitude: renderedViewState.latitude,
        longitude: renderedViewState.longitude,
        visibleLatitude: renderedVisibleCenter.latitude,
        visibleLongitude: renderedVisibleCenter.longitude,
      });
    };
    frame = window.requestAnimationFrame(emit);

    return () => window.cancelAnimationFrame(frame);
  }, [viewState, dimensions, bottomScreenInset, onViewChange]);

  const handleMove = useCallback((evt: { viewState: ViewState }) => {
    setInternalViewState((prev) => {
      const next = evt.viewState;
      // Skip re-render when viewport values haven't changed (e.g. container resize
      // fires move events with identical lat/lng/zoom). Returning the same reference
      // tells React to bail out.
      if (
        prev.latitude === next.latitude &&
        prev.longitude === next.longitude &&
        prev.zoom === next.zoom &&
        prev.pitch === next.pitch &&
        prev.bearing === next.bearing
      ) {
        return prev;
      }
      return next;
    });
  }, []);

  const handleIdle = useCallback(() => {
    if (screenshotMode) window.__map_idle = true;
  }, [screenshotMode]);

  const handleLoad = useCallback(() => {
    setMapReady(true);
  }, []);

  // deck.gl runs interleaved, sharing this canvas's WebGL context. If the browser
  // drops and restores that context, MapLibre rebuilds its own GL resources, but
  // the deck instance keeps buffers/textures from the dead context — the source of
  // the "bufferSubData: no buffer" / "bindTexture: deleted object" errors. Remount
  // the overlay on restore so deck.gl rebuilds against the live context.
  const [deckOverlayKey, setDeckOverlayKey] = useState(0);
  useEffect(() => {
    if (!mapReady) return;
    const canvas = mapRef.current?.getCanvas();
    if (!canvas) return;

    const handleContextLost = (event: Event) => {
      // Let the browser restore the context instead of giving up on it.
      event.preventDefault();
    };
    const handleContextRestored = () => setDeckOverlayKey((key) => key + 1);

    canvas.addEventListener('webglcontextlost', handleContextLost);
    canvas.addEventListener('webglcontextrestored', handleContextRestored);
    return () => {
      canvas.removeEventListener('webglcontextlost', handleContextLost);
      canvas.removeEventListener('webglcontextrestored', handleContextRestored);
    };
  }, [mapReady]);

  const handleFlyTo = useCallback(
    (lat: number, lng: number, zoom: number, options?: MapFlyToOptions) => {
      const targetPoint =
        getViewportRelativeVisibleAreaCenter(dimensions, containerRef.current, options) ??
        getMapRelativeVisibleAreaCenter(dimensions, options);
      const center = getMapCenterForTargetScreenPoint(
        lat,
        lng,
        zoom,
        dimensions.width,
        dimensions.height,
        targetPoint.x,
        targetPoint.y
      );

      // Drive the camera imperatively rather than only through the controlled
      // `viewState` prop. In controlled mode react-map-gl silently DROPS view
      // state updates while the map is mid-movement — _updateViewState writes to
      // the real transform only `if (!map.isMoving())`. So a fly issued right
      // after a scroll-zoom or pan, while inertia is still settling, was being
      // ignored, which is why the jump/zoom only landed sometimes. stop() cancels
      // any in-flight animation/inertia and jumpTo then applies unconditionally;
      // its move events sync `internalViewState` back through handleMove.
      const map = mapRef.current;
      if (map) {
        map.stop();
        map.jumpTo({ center: [center.longitude, center.latitude], zoom });
      } else {
        // Map not mounted yet (e.g. an initial deep-link selection before load):
        // seed the controlled state so it applies once react-map-gl initialises.
        setInternalViewState((prev) => ({ ...prev, ...center, zoom }));
      }
    },
    [dimensions]
  );

  if (flyToRef) flyToRef.current = handleFlyTo;

  const mapStyle = useMemo(() => getMapStyle(theme, basemap), [theme, basemap]);
  const mapDataBeforeId = useMemo(() => getMapDataBeforeId(basemap), [basemap]);
  const maxBounds = useMemo(
    () => getBoundsWithBottomScreenInset(MAP_BOUNDS, MAP_MIN_ZOOM, bottomScreenInset),
    [bottomScreenInset]
  );
  const mapContainerStyle = useMemo<MapContainerStyle>(
    () => (bottomScreenInset > 0 ? { '--map-mobile-bottom-inset': `${bottomScreenInset}px` } : {}),
    [bottomScreenInset]
  );
  const { showLocationSearch, showLegend, topCardsLayoutClass } = useMapCardLayout({
    mapWidth: dimensions.width,
    hideTopCardsWhenNarrow,
    hideLegend,
    hideLocationSearch,
  });
  const getViewportCenter = useCallback(() => {
    const center = mapRef.current?.getCenter();
    return center ? { lat: center.lat, lng: center.lng } : null;
  }, []);

  const {
    layers,
    popupInfo,
    clearPopupInfo,
    visiblePois,
    listingPopup,
    clearListingPopup,
    hoverPosition,
    countRange,
    postcodeCountRange,
    colorFeatureMeta,
    handleMouseLeave,
  } = useDeckLayers({
    data,
    postcodeData,
    usePostcodeView,
    zoom: viewState.zoom,
    pois,
    actualListings,
    viewFeature,
    colorRange,
    filterRange,
    features,
    selectedHexagonId,
    hoveredHexagonId,
    onHexagonClick,
    onHexagonHover,
    theme,
    selectedPostcodeGeometry,
    currentLocation,
    bounds: viewportBounds,
    travelTimeEntries,
    mapDataBeforeId,
    colorOpacity,
  });

  const showAutoPoiCards = !screenshotMode && viewState.zoom >= POI_AUTO_CARD_ZOOM_THRESHOLD;
  const autoPoiCards = useMemo(() => {
    const map = mapRef.current;
    if (!showAutoPoiCards || !mapReady || !map || dimensions.width <= 0 || dimensions.height <= 0) {
      return [];
    }

    return visiblePois.flatMap((poi) => {
      const point = map.project([poi.lng, poi.lat]);
      if (
        !Number.isFinite(point.x) ||
        !Number.isFinite(point.y) ||
        point.x < 0 ||
        point.x > dimensions.width ||
        point.y < 0 ||
        point.y > dimensions.height
      ) {
        return [];
      }
      return [{ poi, x: point.x, y: point.y }];
    });
    // viewState isn't read directly but drives map.project — recompute when the camera moves.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showAutoPoiCards, mapReady, visiblePois, dimensions, viewState]);

  return (
    <div
      className={`flex-1 h-full relative ${bottomScreenInset > 0 ? 'map-has-mobile-bottom-sheet' : ''}`}
      ref={containerRef}
      style={mapContainerStyle}
      onMouseLeave={handleMouseLeave}
    >
      <MapGL
        ref={mapRef}
        {...viewState}
        onMove={handleMove}
        onLoad={handleLoad}
        onIdle={handleIdle}
        mapStyle={mapStyle}
        style={{ width: '100%', height: '100%' }}
        attributionControl={false}
        dragRotate={false}
        touchZoomRotate={true}
        touchPitch={false}
        keyboard={true}
        pitchWithRotate={false}
        minZoom={MAP_MIN_ZOOM}
        maxBounds={maxBounds}
      >
        <OverlayTileLayers
          activeOverlays={activeOverlays}
          activeCrimeTypes={activeCrimeTypes}
          zoom={viewState.zoom}
        />
        <DeckOverlay key={deckOverlayKey} layers={layers} getTooltip={null} />
        {!screenshotMode && <ScaleControl position="bottom-left" maxWidth={100} unit="metric" />}
      </MapGL>
      {basemap === 'satellite' && (
        <div
          className="pointer-events-auto absolute left-2 z-10 max-w-[calc(100%_-_1rem)] rounded bg-white/85 px-1.5 py-0.5 text-[10px] leading-tight text-warm-600 shadow-sm dark:bg-warm-900/85 dark:text-warm-300"
          style={{ bottom: bottomScreenInset > 0 ? bottomScreenInset + 8 : 34 }}
        >
          Sentinel-2 cloudless by EOX, contains modified Copernicus Sentinel data 2024
        </div>
      )}
      {screenshotMode ? (
        ogMode ? (
          <div className="absolute inset-0 z-20 pointer-events-none flex flex-col">
            {/* Center: Logo card with hero text */}
            <div className="flex-1 flex items-center justify-center">
              <div className="flex items-center gap-8 bg-navy-900/90 rounded-3xl px-14 py-10 max-w-[1040px]">
                <LogoIcon className="w-24 h-24 shrink-0 text-teal-400" />
                <span
                  className="font-bold text-white/50"
                  style={{ fontSize: '4rem', lineHeight: 1.05, maxWidth: '760px' }}
                >
                  {t('map.ogTitle')}
                </span>
              </div>
            </div>

            {/* Bottom bar */}
            <div className="absolute bottom-0 left-0 right-0 flex items-center justify-between px-10 py-4 bg-white">
              <div className="flex items-center gap-6">
                <span className="text-warm-500 font-medium" style={{ fontSize: '0.95rem' }}>
                  {t('map.ogPropertyPrices')}
                </span>
                <span className="text-warm-300">|</span>
                <span className="text-warm-500 font-medium" style={{ fontSize: '0.95rem' }}>
                  {t('map.ogEnergyRatings')}
                </span>
                <span className="text-warm-300">|</span>
                <span className="text-warm-500 font-medium" style={{ fontSize: '0.95rem' }}>
                  {t('map.ogSchools')}
                </span>
                <span className="text-warm-300">|</span>
                <span className="text-warm-500 font-medium" style={{ fontSize: '0.95rem' }}>
                  {t('map.ogCrimeStats')}
                </span>
                <span className="text-warm-300">|</span>
                <span className="text-warm-500 font-medium" style={{ fontSize: '0.95rem' }}>
                  {t('map.ogTransport')}
                </span>
              </div>
              <span className="text-teal-600 font-semibold" style={{ fontSize: '1rem' }}>
                perfect-postcode.co.uk
              </span>
            </div>
          </div>
        ) : null
      ) : (
        <>
          {(showLocationSearch || showLegend) && (
            <MapTopCards
              layoutClass={topCardsLayoutClass}
              showLocationSearch={showLocationSearch}
              showLegend={showLegend}
              rightInset={topCardsRightInset}
              onFlyTo={handleFlyTo}
              onLocationSearched={onLocationSearched}
              onCurrentLocationFound={onCurrentLocationFound}
              onLocationSearchMouseEnter={handleMouseLeave}
              getViewportCenter={getViewportCenter}
              viewFeature={viewFeature}
              colorRange={colorRange}
              viewSource={viewSource}
              onCancelPin={onCancelPin}
              onResetPreviewScale={onResetPreviewScale}
              canResetPreviewScale={canResetPreviewScale}
              colorFeatureMeta={colorFeatureMeta}
              usePostcodeView={usePostcodeView}
              countRange={countRange}
              postcodeCountRange={postcodeCountRange}
              densityLabel={densityLabel}
              totalCount={totalCountProp}
              theme={theme}
            />
          )}
          {autoPoiCards.map(({ poi, x, y }) => (
            <div
              key={poi.id}
              className="pointer-events-none absolute bg-white dark:bg-warm-800 rounded-lg shadow-lg text-sm dark:text-white"
              style={{
                left: x,
                top: y - 12,
                transform: 'translate(-50%, -100%)',
                zIndex: 9,
              }}
            >
              <PoiPopupCardContent poi={poi} />
            </div>
          ))}
          {popupInfo && (!showAutoPoiCards || popupInfo.isCluster) && (
            <div
              className="pointer-events-none absolute bg-white dark:bg-warm-800 rounded-lg shadow-lg text-sm dark:text-white"
              style={{
                left: popupInfo.x,
                top: popupInfo.y - 50,
                transform: 'translateX(-50%)',
                zIndex: 30,
              }}
            >
              <button
                className="pointer-events-auto absolute -top-2 -right-2 w-5 h-5 flex items-center justify-center rounded-full bg-warm-200 dark:bg-warm-700 text-warm-500 dark:text-warm-400 hover:text-warm-700 dark:hover:text-warm-300 shadow-sm"
                onClick={clearPopupInfo}
              >
                <CloseIcon className="w-3 h-3" />
              </button>
              {popupInfo.isCluster ? (
                <div className="px-3 py-2 text-center">
                  <div className="text-lg font-bold text-teal-600 dark:text-teal-400">
                    {popupInfo.clusterCount}
                  </div>
                  <div className="text-warm-500 dark:text-warm-400 text-xs">
                    {t('common.places')}
                  </div>
                </div>
              ) : (
                <PoiPopupCardContent poi={popupInfo} />
              )}
            </div>
          )}
          {listingPopup && (
            <div
              className={`pointer-events-auto absolute rounded-lg bg-white text-sm shadow-lg dark:bg-warm-800 dark:text-white ${
                listingPopup.mode === 'cluster' ? 'w-80 max-w-[calc(100vw-2rem)]' : 'max-w-[280px]'
              }`}
              style={{
                left: listingPopup.x,
                top: listingPopup.y - 12,
                transform: 'translate(-50%, -100%)',
                zIndex: 30,
              }}
              onMouseLeave={clearListingPopup}
            >
              <button
                type="button"
                className="pointer-events-auto absolute -top-2 -right-2 w-5 h-5 flex items-center justify-center rounded-full bg-warm-200 dark:bg-warm-700 text-warm-500 dark:text-warm-400 hover:text-warm-700 dark:hover:text-warm-300 shadow-sm"
                onClick={clearListingPopup}
              >
                <CloseIcon className="w-3 h-3" />
              </button>
              {listingPopup.mode === 'single' ? (
                <ListingPopupSingleContent listing={listingPopup.listing} />
              ) : (
                <ListingClusterPopupContent
                  count={listingPopup.count}
                  listings={listingPopup.listings}
                />
              )}
            </div>
          )}
          {hoverPosition && hoveredHexagonId && hoveredHexagonId !== selectedHexagonId && (
            <HoverCardOverlay
              x={hoverPosition.x}
              y={hoverPosition.y}
              id={hoveredHexagonId}
              usePostcodeView={usePostcodeView}
              data={data}
              postcodeData={postcodeData}
              filters={filters}
              features={features}
            />
          )}
        </>
      )}
    </div>
  );
});
